python_14

Matplotlib

import matplotlib.pyplot as plt
import random

from matplotlib.lines import lineStyles

#展示中文
plt.rcParams['font.sans-serif'] = ['SimHei']#设置中文字体为黑体

#目标:绘制折线图
x = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24]
y_bj= [random.randint(10,15) for i in x]
y_xa=[random.randint(13,18) for i in x]

#折线图
plt.figure(figsize=(10,7))
plt.plot(x,y_bj,label='北京')#折线图->如果没有画布,会自动生成一个画布
plt.plot(x,y_xa,label='西安')

#设置折线图的详细信息
plt.title('气温折线图',fontsize=20)#展示图表的标题
plt.xlabel('时间',fontsize=15)#展示图表的X轴的标题
plt.ylabel('气温',fontsize=15)#展示图表的Y轴的标题
plt.xticks(x)#设置X轴的刻度
y_ticks=[i for i in range(0,21)]
plt.yticks(y_ticks)#设置Y轴的刻度
plt.grid(linestyle='--',alpha=0.5)#添加网格
plt.legend(loc='best')

plt.show()#显示图表

子图

from matplotlib.axes import Axes
import matplotlib.pyplot as plt
import random

from pytz import country_timezones

#展示中文
plt.rcParams['font.sans-serif'] = ['SimHei']#设置中文字体为黑体

#创建子图
#柱状图
#figure:画布对象;axes:子图对象(里面存放的是Axes类型的对象
figure,axes=plt.subplots(nrows=1,ncols=2,figsize=(20,6),dpi=100)

#图一:柱状体(世界石油储备)
countries=['中国','美国','日本','印度','俄罗斯']
values=[random.randint(0,10) for i in countries]

axes_1: Axes =axes[0]
axes_1.bar(countries,values,width=0.5,color='g')
axes_1.set_title('世界石油储备')
axes_1.set_xlabel('国家')
axes_1.set_ylabel('油量(亿桶)')

axes_1.grid(linestyle='--',alpha=0.5)
#饼状图
countries=['中国','美国','日本','印度','俄罗斯']
values=[random.randint(1,10) for i in countries]

axes_2: Axes =axes[1]
axes_2.pie(values,labels=countries,autopct='%.1f%%')#饼状图
axes_2.set_title('世界油量占比')
axes_2.legend(loc='best')

#保存图片
plt.savefig('data/01.png')
plt.show()
posted @ 2026-04-05 11:06  鲁国石玉峰  阅读(5)  评论(0)    收藏  举报