画子图(奇数个怎么画?)
比如这样,3X3的排列,只画7个,剩下两个不要:
上面代码如下:
import matplotlib.pyplot as plt
import numpy as np
# N 行 3 列的布局,
total=7 # 假设画7个子图,这里可以随便改
N = int(total / 3) + (0 if total%3 == 0 else 1) # 计算行数
fig, axes = plt.subplots(N, 3, figsize=(6, 4), dpi=150)
# 总共 画7个子图
for idx in range(7):
ax = axes[int(idx/3)][idx%3]
ax.plot(np.arange(10), label='range(10)')
ax.set_title(f'the {idx}-th sugfig')
# 删除最后两个空的子图
fig.delaxes(axes[-1][-1])
fig.delaxes(axes[-1][-2])
handlers, labels = axes[0][0].get_legend_handles_labels()
fig.legend(handlers, labels, loc='lower right')
plt.tight_layout()
plt.show()
subplot 非subplots可以直接参考官网:
(只会用subplot(221)等等之类的都不是真懂)
https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.subplot.html
我也搞不懂为什么搜到的博客都是只会:plt.subplot(221)这种用法。。。
建议大家多多看官方文档,免得被误导。