Python/Gridspec 高度比例问题
我刚开始学习python和matplotlib,遇到了一些麻烦,想调整两个图表的高度。我的目标是让这两个图表垂直排列,一个在上面,一个在下面。下面的图表高度应该是上面图表的一半。如果我使用宽度比例(width_ratios),结果正如我预期的那样(虽然这不是我想要的)。但是当我使用高度比例(height_ratios)时,两个图表却水平排列,并且下面留有空白,那个空白的高度正好是两个图表的一半。下面是相关的代码部分:
pl.figure()
grid = gs.GridSpec(1, 2, height_ratios=[2,1])
ax1 = pl.subplot(grid[0])
ax2 = pl.subplot(grid[1])
我相信我做的事情很简单(可能还有点傻),但作为新手的我就是看不出来。
2 个回答
3
这两个的比例是3:1:
import matplotlib.pyplot as plt
# left bott width height
rect_bot = [0.1, 0.1, 0.8, 0.6]
rect_top = [0.1, 0.75, 0.8, 0.2]
plt.figure(1, figsize=(8,8))
bot = plt.axes(rect_bot)
top = plt.axes(rect_top)
bot.plot([3, 2, 60, 4, 7])
top.plot([2, 3, 5, 3, 2, 4, 6])
plt.show()
你可以调整 rect_top
和 rect_bot
的底部坐标和高度,来获得你想要的比例和外观。下面的方法可以快速改变比例,只需修改 ratio
的值。这将给你期望的比例(1:2):
left, width = 0.1, 0.8
ratio = 2
border = 0.1
total = 1
bh = (total - 3 * border) / (total + ratio)
th = ratio * bh
tb = bh + 2 * border
# left bott width height
rect_bot = [left, border, w, bh]
rect_top = [left, tb, width, th]
2
你在Gridspec语句中把行和列的位置搞错了:
grid = gs.GridSpec(2,1 , height_ratios=[2,1])
这样做就可以了。