Python 在 matplotlib 中设置子图的大小

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41530975/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 01:11:27  来源:igfitidea点击:

Set size of subplot in matplotlib

pythonmatplotlibsubplot

提问by Andrej

I wonder how to set the size of the subplot when figure contains multiple subplots (5 × 2 in my case). No matter how big I allow the whole figure to be, the subplots always seem to be small. I would like to have direct control of the size of the subplot in this figure. The simplified version of the code is pasted below.

我想知道当图形包含多个子图(在我的情况下为 5 × 2)时如何设置子图的大小。无论我允许整个图形有多大,次要情节似乎总是很小。我想直接控制此图中子图的大小。代码的简化版本粘贴在下面。

import numpy as np
import matplotlib.pyplot as plt

x = np.random.randn(20)
y = np.random.randn(20)

fig = plt.figure(figsize=(20, 8))

for i in range(0,10):
    ax = fig.add_subplot(5, 2, i+1)
    plt.plot(x, y, 'o')
    ax.xaxis.set_visible(False)
    ax.yaxis.set_visible(False)
    # x and y axis should be equal length
    x0,x1 = ax.get_xlim()
    y0,y1 = ax.get_ylim()
    ax.set_aspect(abs(x1-x0)/abs(y1-y0))

plt.show()
fig.savefig('plot.pdf', bbox_inches='tight')

回答by Mike Müller

Just switch figure size width and height from:

只需从以下位置切换图形大小的宽度和高度:

fig = plt.figure(figsize=(20, 8))

to:

到:

fig = plt.figure(figsize=(8, 20))

to use the whole page for your plots.

将整个页面用于您的绘图。

This will change your plot from:

这将改变你的情节:

enter image description here

在此处输入图片说明

to:

到:

enter image description here

在此处输入图片说明