matplotlib库的基本使用与折线图

matplotlib:最流行的Python底层绘图库,主要做数据可视化图表,名字取材于MATLAB,模仿MATLAB构建

 

基本使用:

  • x和y的长度必须一致
  • figure()方法用来设置图片大小
  • x,y轴的刻度用可迭代对象进行设置,步长影响刻度的密集程度
 1 from matplotlib import pyplot as plt
 2 
 3 
 4 x = range(2, 26, 2)
 5 y = [15, 13, 14.5, 17, 20, 25, 26, 26, 24, 22, 18, 15]
 6 
 7 #设置图片大小
 8 plt.figure(figsize=(16, 8), dpi=80)
 9 
10 # 设置x轴的刻度,步长决定x轴的密集程度,也可以用列表推导式(涉及到小数的时候就要用列表了)
11 plt.xticks(range(2, 26, 2))  # 等同于:[x for x in range(2, 26, 2)]
12 plt.yticks(range(min(y), max(y)+1))  # 设置y轴的刻度,这样设置比较合适
13 
14 plt.plot(x, y)  # 绘图
15 plt.savefig('./t1.png')  # 保存
16 plt.show()  # 展示图形

 

题目:如果列表a表示10点到12点的每一分钟的气温,绘制折线图观察每分钟气温的变化
a = [random.randint(20, 35) for i in range(120)]

  • matplotlib库默认不支持中文,需要配置,下面是其中一种方法
  • 刻度设置为字符串的时候,字符串列表必须与原数字刻度列表长度一致
 1 import random
 2 from matplotlib import pyplot as plt
 3 import matplotlib
 4 
 5 # windows和linux可以这样让其支持中文
 6 font = {
 7     'family': 'MicroSoft YaHei',
 8     'weight': 'bold',
 9 }
10 matplotlib.rc('font', **font)
11 
12 
13 # 如果列表a表示10点到12点的每一分钟的气温,绘制折线图观察每分钟气温的变化
14 # a = [random.randint(20, 35) for i in range(120)]
15 x = range(120)
16 y = [random.randint(20, 35) for i in range(120)]
17 
18 plt.figure(figsize=(20, 8), dpi=80)  # 设置图片大小
19 
20 # 调整x轴的刻度
21 _xtick_label = ['10点{}分'.format(i) for i in range(60)]
22 _xtick_label += ['11点{}分'.format(i) for i in range(60)]
23 # 取步长,数字和字符串一一对应,数据的长度一样,原先第一个参数对应的数字变为第二个参数的字符串,rotation使字符串旋转90度
24 plt.xticks(list(x)[::5], _xtick_label[::5], rotation=45)  # 转化为列表,列表可以取步长,两个参数的长度必须一致
25 
26 # 添加描述信息
27 plt.xlabel('时间')
28 plt.ylabel('温度/单位(摄氏度)')
29 plt.title('10点到12点每分钟气温的变化情况')
30 
31 plt.plot(x, y)
32 plt.show()

猜你喜欢

转载自www.cnblogs.com/springionic/p/11145932.html