gpt4 book ai didi

python - matplotlib 5 方形子图

转载 作者:太空宇宙 更新时间:2023-11-04 05:38:37 27 4
gpt4 key购买 nike

我正在尝试使用 matplotlib 并排绘制 5 组数据,但收效甚微。无论我使用 subplot2grid 还是简单的 subplot,我似乎都无法避免得到瘦削的图表。我想要 5 个并排的图表,高度:宽度为 1:1。我使用 range() 只是为了简单起见(我可以成功地在单个图中绘制我的数据)

x = range(10)
y = range(10,20,1)
a1 = plt.subplot(151)
a1.plot(y,x)

a2 = plt.subplot(152)
a2.plot(x,y)

a3 = plt.subplot(153)
a3.plot(x,y)

a4 = plt.subplot(154)
a4.plot(x,y)

a5 = plt.subplot(155)
a5.plot(x,y)

我打算使用 将它保存为 pdf

with PdfPages('fname.pdf') as pdf:
plt.close('all')
fig = plt.figure()

script_for_plots_like_above()

plt.tight_layout()
pdf.savefig(fig)

但现在我只想要并排的数字。感谢您的帮助!

最佳答案

这里有两个问题:

  1. 使地 block 呈正方形。
  2. 使 Canvas 大小适合您的绘图。

要使绘图呈正方形,您可以在每个轴上使用 ax.set_aspect('equal')。例如:

import matplotlib.pyplot as plt

plt.figure()
x = range(10)
y = range(10,20,1)

a1 = plt.subplot(151)
a1.plot(y,x)
a1.set_aspect('equal')

a2 = plt.subplot(152)
a2.plot(x,y)
a2.set_aspect('equal')

a3 = plt.subplot(153)
a3.plot(x,y)
a3.set_aspect('equal')

a4 = plt.subplot(154)
a4.plot(x,y)
a4.set_aspect('equal')

a5 = plt.subplot(155)
a5.plot(x,y)
a5.set_aspect('equal')

plt.savefig('plots-with-aspect.png')

产生以下情节:

enter image description here

请注意,这些地 block 现在是方形的,但它们位于大量空白区域的中间。您想要使用 figsize=(x,y) 调整绘图的大小以适应坐标轴,例如

import matplotlib.pyplot as plt

plt.figure(figsize=(5*5, 5))
x = range(10)
y = range(10,20,1)

a1 = plt.subplot(151)
a1.plot(y,x)
a1.set_aspect('equal')

a2 = plt.subplot(152)
a2.plot(x,y)
a2.set_aspect('equal')

a3 = plt.subplot(153)
a3.plot(x,y)
a3.set_aspect('equal')

a4 = plt.subplot(154)
a4.plot(x,y)
a4.set_aspect('equal')

a5 = plt.subplot(155)
a5.plot(x,y)
a5.set_aspect('equal')

plt.savefig('plots-with-aspect-size.png')

产生以下情节:

enter image description here

请注意,大小是相对于每个轴中的轴数计算的。

要进一步调整情节以适合图像,例如,您可以在保存时设置紧凑的布局,例如

plt.savefig('plots-with-aspect-size-tight.png', bbox_inches='tight')

产生:

enter image description here

关于python - matplotlib 5 方形子图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34815622/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com