1、基本要点
# 导入模块 from matplotlib import pyplot as plt # x轴数据 x = range(2, 26, 2) # y轴数据 y = [15, 13, 14.5, 17, 20, 25, 26, 26, 27, 22, 18, 15] # 绘图 plt.plot(x, y) # 展示图片 plt.show()
注意: x轴和y轴是可迭代对象,x轴和y轴的数值必须一一对应
2、设置图行大小
plt.figure(figsize=(宽, 高), dpi=80) # 注意:设置图形大小,要在绘图的前面
3、保存图片
plt.savefig('./名称.png')
# 注意:
# 保存图片要在,绘图之后
# 可以保存为矢量图(svg)
4、调整x轴或y轴上的刻度
plt.xticks(可迭代对象) plt.yticks(可迭代对象) # 注意: # 调整x轴或y轴的刻度,要放在保存或展示图片的前面
例子
# 导入模块
from matplotlib import pyplot as plt
# x轴数据
x = range(2, 26, 2)
# y轴数据
y = [15, 13, 14.5, 17, 20, 25, 26, 26, 27, 22, 18, 15]
# 设置图形大小
plt.figure(figsize=(20, 8), dpi=80)
# 绘图
plt.plot(x, y)
# 调整x轴的刻度
plt.xticks(x)
# 调整y轴的刻度
plt.yticks(range(min(y), max(y) + 1))
# 保存图片
# plt.savefig('./test.svg')
# 展示图片
plt.show()
5、调整x轴或y轴的刻度并显示标签
plt.xticks(ticks, labels, rotation=45) # 注意 # ticks和labels的数据类型最好是列表,方便调整刻度 # ticks和labels即数字和字符串要一一对应,步长也要一致 # rotation调整标签的旋转
例子
import random
from matplotlib import pyplot as plt
y = [random.randint(20, 35) for i in range(120)]
x = range(120)
# 设置图形大小
plt.figure(figsize=(20, 8), dpi=80)
# 绘图
plt.plot(x, y)
# 设置x轴刻度
x = list(x)
x_labels = ['10H:{}M'.format(i) for i in range(60)]
x_labels += ['11H:{}M'.format(i) for i in range(60)]
plt.xticks(x[::3], x_labels[::3], rotation=45)
# 设置y轴刻度
plt.yticks(range(min(y), max(y) + 1))
# 展示图片
plt.show()
6、显示中文
a、查看字体
linux/mac查看支持的字体 fc-list # 查看支持的字体 fc-list :lang=Zhang # 查看支持的中文(冒号前面加空格) windows查看支持的字体 Win+R, 输入fonts 获取字体路径: 推荐使用git bash 查看字体 cd 'C:\Windows\Fonts' ls -l 一般使用 msyh.ttc
b、设置
修改matplotlib的默认字体
1.matplotlib.rc,具体看源码(windows/linux),不是百分百成功
2.matplotlib下的font_manager(windwos/linux/mac),百分百成功
# 导入模块 from matplotlib import font_manager # 设置显示中文 my_font = font_manager.FontProperties(fname='C:\Windows\Fonts\msyh.ttc') # 添加fontproperties=my_font的属性 plt.xticks(x[::3], x_labels[::3], rotation=45, fontproperties=my_font) # 注意: 设置中文显示时 # 只有plt.legend, 使用prop # 其它使用fontproperties
例子
import random
from matplotlib import pyplot as plt
from matplotlib import font_manager
# 设置显示中文
my_font = font_manager.FontProperties(fname='C:\Windows\Fonts\msyh.ttc')
y = [random.randint(20, 35) for i in range(120)]
x = range(120)
# 设置图形大小
plt.figure(figsize=(20, 8), dpi=80)
# 绘图
plt.plot(x, y)
# 设置x轴刻度,显示标签(中文)
x = list(x)
x_labels = ['10时:{}分'.format(i) for i in range(60)]
x_labels += ['11时:{}分'.format(i) for i in range(60)]
plt.xticks(x[::3], x_labels[::3], rotation=45, fontproperties=my_font)
# 设置y轴刻度
plt.yticks(range(min(y), max(y) + 1))
# 展示图片
plt.show()
7、