【问题标题】:How can I increase the height (size) and space between subplots in python如何增加python中子图之间的高度(大小)和空间
【发布时间】:2020-07-28 08:40:04
【问题描述】:

我想要两个大小相等的子图并增加第三个子图的高度(大小)。此外,我的第三个情节坚持我的第二个子情节。我想在第二个和第三个子图之间有一个小的距离。我应该提一下,我的 X 轴对于所有子图都是通用的。这是我的代码的一部分。

from datetime import datetime, timedelta
from matplotlib import pyplot as plt
from matplotlib import dates as mpl_dates

ax1 = plt.subplot(311)
plt.plot(date,amount, color='gray', linewidth=0.3)
plt.ylabel('2-4 Hz')

   
ax2 = plt.subplot(312)
plt.plot(date,amount, color='brown', linewidth=0.3)
plt.ylabel('0.4-2 Hz')

ax3 = plt.subplot(313)
plt.bar (date, amount, color='gold', edgecolor='red', align='center')
plt.ylabel('rainfall(mm/day)')

ax1.get_shared_x_axes().join(ax1, ax2, ax3)
plt.subplots_adjust(hspace=0.01)


plt.show()

enter image description here

【问题讨论】:

    标签: python matplotlib subplot


    【解决方案1】:

    我会使用plt.subplots() 中的gridspec_kw 参数来解决这个问题,然后在第二轴和第三轴之间手动添加一点空间。 gridspec_kw 可让您设置每个轴的高度比。

    可能有更好的方法来添加第二轴和第三轴之间的空间,但我认为这符合您的需求。

    fig, ax = plt.subplots(3, 1, sharex=True, gridspec_kw={'height_ratios':[1,1,2]})
    fig.subplots_adjust(hspace=0.0)
    ax1 = ax[0]
    ax2 = ax[1]
    ax3 = ax[2]
    bbox = list(ax3.get_position().bounds)
    bbox[3] = 0.9*bbox[3] # Reduce the height of the axis a bit.
    ax3.set_position(bbox)
    
    ax1.plot(date,amount, color='gray', linewidth=0.3)
    ax1.set_ylabel('2-4 Hz')
    
    ax2.plot(date,amount, color='brown', linewidth=0.3)
    ax2.set_ylabel('0.4-2 Hz')
    
    ax3.bar (date, amount, color='gold', edgecolor='red', align='center')
    ax3.set_ylabel('rainfall(mm/day)')
    
    

    【讨论】:

    • 感谢您的回复,我根据您的建议更改了代码。高度增加了,子图之间的空间也增加了,但是我的前两个子图变空了,这两个图的范围也发生了变化。范围应该在 (-2,2) 之间,而当前范围是 (0,2) !
    • 请查看编辑后的答案,看看是否适合您。