本文介绍matplotlib绘图方法,包括应用于Jupyter Notebook和Linux服务器脚本(无图形显示,因此需要保存到本地才能看到图片)的场景。
官方文档(很不好用):Matplotlib documentation — Matplotlib 3.6.2 documentation
官方教程(贼难用):Pyplot tutorial — Matplotlib 3.7.1 documentation
安装代码:pip install matplotlib
通用导包代码:
%matplotlib inline
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
(第一行是jupyter notebook用的)
字体,如果没有相应的系统字体,需要手动指定字体文件的位置,请参考本文第4章字体的介绍。
文章目录
1. 简单的完整示例
1. 组合图
- 画2个折线图保存到本地,起中文标题,每张图都画两条折线,附中文图例。但是电脑上没有中文字体,所以使用用户路径下的字体文件
示例图1:
示例图2:
import random
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
loss1=[random.gauss(mu=10,sigma=1) for _ in range(10)]
loss2=[random.gauss(mu=11,sigma=1) for _ in range(10)]
acc1=[random.uniform(0.5,0.6) for _ in range(10)]
acc2=[random.uniform(0.4,0.5) for _ in range(10)]
font = FontProperties(fname='other_data_temp/simkai.ttf')
plt.rcParams['axes.unicode_minus']=False
plt.title('示例图片1:模拟模型双损失函数绘图',fontproperties=font)
plt.plot(loss1, label="训练集loss")
plt.plot(loss2, label="验证集loss")
plt.legend(prop=font)
plt.savefig('try1.png')
plt.close() #为了防止多图冲突
plt.title('示例图片2:模拟模型双accuracy绘图',fontproperties=font)
plt.plot(acc1, label="训练集acc")
plt.plot(acc2, label="验证集acc")
plt.legend(prop=font)
plt.savefig('try2.png')
plt.close()
- 分别画2个折线图,但是呈现在同一个画布里面
示例图像:
import random
import matplotlib.pyplot as plt
loss1=[random.gauss(mu=10,sigma=1) for _ in range(10)]
acc1=[random.uniform(0.5,0.6) for _ in range(10)]
plt.figure()
plt.subplot(211)
plt.plot(loss1,label='loss')
plt.legend()
plt.subplot(212)
plt.plot(acc1,label='acc')
plt.legend()
plt.savefig('try2.png')
plt.close()
- 画组合图:在图中画不同x/y刻度的柱形图和折线图,其他配置与上图类似(注意这个
plt.title()
如果位置放得太靠前会导致标题显示不出来)
示例图像:
import random
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
font = FontProperties(fname='other_data_temp/simkai.ttf')
x=[i for i in range(10)]
y1=[random.gauss(mu=10,sigma=1) for _ in range(10)]
y2=[random.uniform(0,1) for _ in range(10)]
plt.rcParams['figure.figsize'] = (12,5)
#画柱形图
fig,ax1=plt.subplots()
ax1.bar(x,y1,alpha=.7,color='g')
ax1.set_ylabel('损失函数',fontsize='15',fontproperties=font)
#画折线图
ax2=ax1.twinx() #组合图必须加这个
ax2.plot(x,y2,'r',ms=10)
ax2.set_ylabel('ACC',fontsize='15',fontproperties=font)
plt.title('示例图片:模拟柱形图损失函数+折线图ACC共图',fontproperties=font)
plt.savefig('try2.png')
2. 可视化graph
import matplotlib.pyplot as plt
import networkx as nx
# 定义两个edge index
edge_index1 = [[0, 0, 1, 1, 1, 2, 2, 2, 3, 3], [1, 2, 2, 2, 0, 3, 3, 0, 1, 1]]
edge_index2 = [[0, 0, 1, 2, 3, 1, 2, 2, 3, 1], [1, 2, 2, 3, 1, 0, 0, 1, 2, 3]]
# 创建图
G1 = nx.DiGraph()
G2 = nx.DiGraph()
# 添加边
for start, end in zip(*edge_index1):
G1.add_edge(start, end)
for start, end in zip(*edge_index2):
G2.add_edge(start, end)
# 绘图
plt.figure(figsize=(12, 6))
# 绘制第一个图
plt.subplot(121)
nx.draw(G1, with_labels=True, node_color='skyblue', node_size=700, arrowstyle='->', arrowsize=20)
# 绘制第二个图
plt.subplot(122)
nx.draw(G2, with_labels=True, node_color='lightgreen', node_size=700, arrowstyle='->', arrowsize=20)
plt.show()
2. 绘图 plot()
:绘制各种图形用什么函数
除了在plt上之外,还可以放到轴上。
- 折线图
plt.plot(y)
:x就是y的元素索引plt.plot(x,y)
- 柱形图
plt.bar(x,y)
- 箱型图
plt.boxplot(x)
- 散点图
plt.scatter(x,y)
- 其他属性
label
:图例color
:设置颜色(可以参考How to set Color for Bar Plot in Matplotlib?一文markersize
或ms
3. 保存到本地和展示
plt.savefig(图片名)
参数bbox_inches='tight'
:去除白边1
- 连存多张图片时,每一张写完都要写
plt.close()
,否则上一张会画到下一张上
4. 字体
字体对象:
from matplotlib.font_manager import FontProperties
font = FontProperties(fname='字体文件位置',size=30)
在plt.title()
、set_ylabel()
、plt.xticks
中用fontproperties
参数传入
在plt.legend()
中用prop
参数传入
5. plt
其他函数
plt.title(标题名)
fontproperties
:字体对象
plt.subplots()
set_ylabel(标签名)
fontsize
fontproperties
:字体对象
- 设置x轴的tick(显示的字):
plt.xticks(原tick,新tick)
- 设置tick的参数(字体大小等):
plt.tick_params(axis="y",labelsize=16)
- 设置坐标轴的范围:
plt.xlim(下限,上限)
plt.ylim(下限,上限)
- 在图表上的特定位置放置文本:
plt.text(x,y,文字,fontproperties=font, ha='center', va='bottom')
ha='center'
和va='bottom'
选项分别控制水平和垂直对齐,以确保文本整齐地显示在每个点的上方。
6. plt
基础设置
- 设置图形大小:
plt.rcParams['figure.figsize'] = (12,5)
7. 其他参考资料
- matplotlib:次坐标轴ax2=ax1.twinx()_Marina-ju的博客-CSDN博客_ax1.twinx()
- Matplotlib - 箱线图、箱型图 boxplot () 所有用法详解_黄饱饱_bao的博客-CSDN博客
- 【数据分析之道-Matplotlib(四)】Matplotlib散点图_matplotlib画散点_i阿极(暂时无法回复版)的博客-CSDN博客
- 设置Matplotlib图表中的坐标轴范围是进行数据可视化的重要步骤之一。在本文中,我们将探讨如何在Python中设置X轴的下限和上限数值。_matplotlib 设置坐标轴范围-CSDN博客