python-matplotlib画图

matplotlib画图

https://matplotlib.org/

https://zhuanlan.zhihu.com/p/109245779

简洁优雅的Matplotlib可视化 | 绘制论文曲线图:https://zhuanlan.zhihu.com/p/81336415

  • 训练的loss可视化
1
2
3
4
5
6
7
8
9
10
11
12
def plot_train_history(train_loss_history, val_loss_history, save_title):
save_path = "/home/lizy/ml/Malware_Adversarial_Ensemble/figures/"
fig, ax = plt.subplots()
time_ = range(len(train_loss_history))
ax.set_xlabel("Epochs")
ax.set_ylabel("BCE Loss")
ax.grid(linestyle="--")
ax.plot(time_, train_loss_history, color="blue", label="train loss")
ax.plot(time_, val_loss_history, color="red", label="val loss")
ax.legend(loc="best")
fig.savefig(os.path.join(save_path, f"{save_title}_train_history.png"), dpi=300)
plt.close(fig)
  • 绘制三个折线子图
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import matplotlib.pyplot as plt

def plot_subplots(data):
# 数据
x = data['x']
ys = data['ys']
labels = data['labels']

# 创建一个1x3的子图布局,并设置整个图形的大小
fig, axs = plt.subplots(1, 3, figsize=(15, 4))

# 绘制每个子图
for i, ax in enumerate(axs):
for j, y in enumerate(ys[i]):
ax.plot(x, y, label=labels[j])
ax.set_title(f'Subplot {i+1}')
ax.legend()

# 设置图的标题
fig.suptitle('Three subplots with shared legend')

# 调整子图布局和间距
fig.subplots_adjust(wspace=0.2)

# 显示图形
plt.show()