matplotlib 简介
Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python.
Matplotlib makes easy things easy and hard things possible.
matplotlib is a Matlab alternative
基本折线图
code:
# 导入库
from matplotlib import pyplot as plt
# x、y 均为可迭代对象
x = range(2, 26, 2)
y = [15, 13, 14.5, 17, 20, 25, 26, 26, 24, 22, 18, 15]
# 绘制
plt.plot(x, y)
plt.show()
结果:
troubleshooting
如果 pycharm 遇到:
AttributeError: module 'backend_interagg' has no attribute 'FigureCanvas'
尝试去掉勾选如下配置:
参考:https://stackoverflow.com/questions/51214140/attributeerror-figurecanvasinteragg-object-has-no-attribute-renderer
调整画布
# 设置画布大小 dpi
plt.figure(figsize=(20, 8), dpi=80)
# 保存图片
plt.savefig("./sig_size.png")
plt.savefig("./sig_size.svg")
调整坐标刻度
# 绘制要显示的坐标刻度
plt.xticks(range(2, 25))
plt.xticks([i/2 for i in range(4, 49)])
生成随机数据
x = range(0, 120)
y = [random.randint(20, 35) for i in range(120)]
坐标使用字符串数组 & 数据切片
# 按照 x 步长 slices
_x = list(x)
# y 轴用自定义模板字符串
_xticks_labels = ["10点{}分".format(i) for i in range(60)]
_xticks_labels += ["11点{}分".format(i) for i in range(60)]
plt.xticks(_x[::3], _xticks_labels[::3], rotation=90)
list(x) 才支持切片 参考 slices: https://stackoverflow.com/questions/9027862/what-does-listxy-do
支持中文编码
# 查看可用字体
fc-list
# 查看中文字体
fc-list lang=zh
使用 matplotlib.rc(), 注意参考rc()源码:
# rc 属性配置
font = {'family': 'Heiti SC',
'weight': 'bold',
'size': 12}
matplotlib.rc('font', **font)
# 另外一种中文字体设置方式
my_font = font_manager.FontProperties(fname="/System/Library/Fonts/PingFang.ttc")
其他方案,参考:https://www.zhihu.com/question/25404709
from mplfonts import use_font
use_font('Noto Sans CJK SC')#指定中文字体
添加描述信息
# 添加描述信息
plt.xlabel("时间")
plt.ylabel("温度 单位(c)")
plt.title("10点到12点每分钟的气温变化情况")
绘制网格
plt.grid(alpha=0.4)
绘制多图 & 图例
# 多图
plt.plot(x,y_1,label="自己",color="#F08080")
plt.plot(x,y_2,label="同桌",color="#DB7093",linestyle="--")
# 图例
plt.legend(prop=my_font,loc="upper left")