完整代码

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
28
29
30
31
32
33
34
35
36
37
38
39
import numpy as np
import matplotlib.pyplot as plt

folder_name = f"plot/c{cost_value}logs.txt"
tpl = np.loadtxt(folder_name, delimiter=' ',unpack=True) # 读取一行
dc_data[cost_value] = tpl[-3]

def main():
plt.rcParams['xtick.direction'] = 'in' # 将x周的刻度线方向设置向内
plt.rcParams['ytick.direction'] = 'in' # 将y轴的刻度线方向设置向内
plt.rcParams['font.sans-serif'] = ['Times New Roman'] # 设置字体
plt.rcParams['figure.figsize'] = (12, 10) # 设置图片大小


cost_values = ["1.5", "1", "0.5", "0.1"]
x_tick = np.array([2, 3, 4, 5, 6, 7, 8, 9], dtype=int)
types = [f"$c$={cost_value}" for cost_value in cost_values]

dc_data, fig_name, (xlabel, ylabel), ylim_tuple = quality(
cost_values)

markers = ['>', 'x', 'o', "d"]
for idx, cost_value in enumerate(cost_values):
plt.plot(x_tick, dc_data[cost_value],
label=types[idx], marker=markers[idx], linewidth=3, markersize=12, markeredgewidth=5)

plt.xlabel(xlabel, fontsize=30) # 横坐标名字
plt.ylabel(ylabel, fontsize=30) # 纵坐标名字
plt.xticks(fontproperties='Times New Roman', size=23) # 设置 tick 属性
plt.yticks(fontproperties='Times New Roman', size=23)
plt.legend(loc="best", ncol=2, prop={
'family': 'Times New Roman', 'size': 23}) # 设置图例属性
plt.grid() # 设置x y 轴网格
plt.xlim(2, 9)
# plt.semilogy() # y轴取对数
plt.ylim(ylim_tuple) # 限制y轴长度 0.9*1e5, 1.0*1e5
plt.savefig(fig_name, dpi=300, bbox_inches='tight')
# plt.show()

  1. numpy 读取数据,方便快捷,后期处理也方便
  2. 刻度线向内
  3. 设置字体
  4. y 轴图像/折线间隔过度稀疏或稠密,对 y 轴取对数
  5. 对折线或者柱状图设置 marker 及其大小,看起来内容更充足
  6. 设置 y 轴的范围,拉长或者缩短 y 轴
  7. plt.savefig('fig.png',dpi=300, bbox_inches='tight') 以 dpi 300 的清晰度保存图片,同时通过 bbox_inches='tight' 选项设置去除图片四周无用空白

注: plt.tight_layout() 不经常有用,只用 bbox_inches='tight' 即可。

python - Matplotlib Error: "figure includes Axes that are not compatible with tight_layout" - Stack Overflow