在 Python 中的 matplotlib 中调整单个子图的高度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3330137/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
adjusting heights of individual subplots in matplotlib in Python
提问by
if I have a series of subplots with one column and many rows, i.e.:
如果我有一系列一列多行的子图,即:
plt.subplot(4, 1, 1) # first subplot
plt.subplot(4, 1, 2) # second subplot
# ...
how can I adjust the height of the first N subplots? For example, if I have 4 subplots, each on its own row, I want all of them to have the same width but the first 3 subplots to be shorter, i.e. have their y-axes be smaller and take up less of the plot than the y-axis of the last plot in the row. How can I do this?
如何调整前 N 个子图的高度?例如,如果我有 4 个子图,每个子图都在自己的行上,我希望它们都具有相同的宽度,但前 3 个子图更短,即它们的 y 轴更小,占用的图少于行中最后一个图的 y 轴。我怎样才能做到这一点?
thanks.
谢谢。
采纳答案by Joe Kington
There are multiple ways to do this. The most basic (and least flexible) way is to just call something like:
有多种方法可以做到这一点。最基本(也是最不灵活)的方法是调用类似的东西:
import matplotlib.pyplot as plt
plt.subplot(6,1,1)
plt.subplot(6,1,2)
plt.subplot(6,1,3)
plt.subplot(2,1,2)
Which will give you something like this:

这会给你这样的东西:

However, this isn't very flexible. If you're using matplotlib >= 1.0.0, look into using GridSpec. It's quite nice, and is a much more flexible way of laying out subplots.
但是,这不是很灵活。如果您使用的是 matplotlib >= 1.0.0,请考虑使用GridSpec。它非常好,并且是布置子图的更灵活的方式。
回答by benjaminmgross
Even though this question is old, I was looking to answer a very similar question. @Joe's reference to AxesGrid, was the answer to my question, and has verystraightforward usage, so I wanted to illustrate that functionality for completeness.
即使这个问题很老,我也想回答一个非常相似的问题。@Joe对AxesGrid的引用是我问题的答案,并且用法非常简单,因此我想说明该功能的完整性。
AxesGridfunctionality provides the ability create plots of different size and place them very specifically, via the subplot2gridfunctionality:
AxesGrid功能提供了通过以下subplot2grid功能创建不同大小的绘图并非常具体地放置它们的能力:
import matplotlib.pyplot as plt
ax1 = plt.subplot2grid((m, n), (row_1, col_1), colspan = width)
ax2 = plt.subplot2grid((m, n), (row_2, col_2), rowspan = height)
ax1.plot(...)
ax2.plot(...)
Note that the max values for row_n,col_nare m-1and n-1respectively, as zero indexing notation is used.
注意,对于最大值row_n,col_n是m-1与n-1分别作为零索引符号被使用。
Specifically addressing the question, if there were 5 total subplots, where the last subplot has twice the height as the others, we could use m=6.
具体解决这个问题,如果总共有 5 个子图,其中最后一个子图的高度是其他子图的两倍,我们可以使用m=6.
ax1 = plt.subplot2grid((6, 1), (0, 0))
ax2 = plt.subplot2grid((6, 1), (1, 0))
ax3 = plt.subplot2grid((6, 1), (2, 0))
ax4 = plt.subplot2grid((6, 1), (3, 0))
ax5 = plt.subplot2grid((6, 1), (4, 0), rowspan=2)
plt.show()



