matplotlib画图(持续更新ing...)

诸神缄默不语-个人CSDN博文目录

本文介绍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. 组合图

  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()
  1. 分别画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()
  1. 画组合图:在图中画不同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上之外,还可以放到轴上。

  1. 折线图
    1. plt.plot(y):x就是y的元素索引
    2. plt.plot(x,y)
  2. 柱形图
    1. plt.bar(x,y)
  3. 箱型图
    1. plt.boxplot(x)
  4. 散点图
    1. plt.scatter(x,y)
  5. 其他属性
    1. label:图例
    2. color:设置颜色(可以参考How to set Color for Bar Plot in Matplotlib?一文
    3. markersizems

3. 保存到本地和展示

  1. plt.savefig(图片名)
    参数
    1. bbox_inches='tight':去除白边1
  2. 连存多张图片时,每一张写完都要写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其他函数

  1. plt.title(标题名)
    1. fontproperties:字体对象
  2. plt.subplots()
  3. set_ylabel(标签名)
    1. fontsize
    2. fontproperties:字体对象
  4. 设置x轴的tick(显示的字):plt.xticks(原tick,新tick)
  5. 设置tick的参数(字体大小等):plt.tick_params(axis="y",labelsize=16)
  6. 设置坐标轴的范围:plt.xlim(下限,上限)  plt.ylim(下限,上限)
  7. 在图表上的特定位置放置文本:plt.text(x,y,文字,fontproperties=font, ha='center', va='bottom')
    ha='center'va='bottom' 选项分别控制水平和垂直对齐,以确保文本整齐地显示在每个点的上方。

6. plt基础设置

  1. 设置图形大小:plt.rcParams['figure.figsize'] = (12,5)

7. 其他参考资料

  1. matplotlib:次坐标轴ax2=ax1.twinx()_Marina-ju的博客-CSDN博客_ax1.twinx()
  2. Matplotlib - 箱线图、箱型图 boxplot () 所有用法详解_黄饱饱_bao的博客-CSDN博客
  3. 【数据分析之道-Matplotlib(四)】Matplotlib散点图_matplotlib画散点_i阿极(暂时无法回复版)的博客-CSDN博客
  4. 设置Matplotlib图表中的坐标轴范围是进行数据可视化的重要步骤之一。在本文中,我们将探讨如何在Python中设置X轴的下限和上限数值。_matplotlib 设置坐标轴范围-CSDN博客

  1. 去除plt.savefig()的白边 Removing white space around a saved image in matplotlib_plt。savefig去白天-CSDN博客 ↩︎

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

诸神缄默不语

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值