如何使用 Python 并排绘制两个图?

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

How to make two plots side-by-side using Python?

pythonmatplotlib

提问by Hei?enberg93

I found the following example on matplotlib:

我在 matplotlib 上找到了以下示例:

import numpy as np
import matplotlib.pyplot as plt


x1 = np.linspace(0.0, 5.0)
x2 = np.linspace(0.0, 2.0)

y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
y2 = np.cos(2 * np.pi * x2)

plt.subplot(2, 1, 1)
plt.plot(x1, y1, 'ko-')
plt.title('A tale of 2 subplots')
plt.ylabel('Damped oscillation')


plt.subplot(2, 1, 2)
plt.plot(x2, y2, 'r.-')
plt.xlabel('time (s)')
plt.ylabel('Undamped')

plt.show()

My question is: What do i need to change, to have the plots side-by-side?

我的问题是:我需要改变什么,让这些情节并排?

回答by Jonathan Eunice

Change your subplot settings to:

将您的子图设置更改为:

plt.subplot(1, 2, 1)

...

plt.subplot(1, 2, 2)

The parameters for subplotare: number of rows, number of columns, and which subplot you're currently on. So 1, 2, 1means "a 1-row, 2-column figure: go to the first subplot." Then 1, 2, 2means "a 1-row, 2-column figure: go to the second subplot."

参数为subplot:行数、列数以及您当前所在的子图。所以1, 2, 1意思是“一个 1 行 2 列的图形:转到第一个子图。” 然后1, 2, 2表示“一个 1 行 2 列的图形:转到第二个子图。”

You currently are asking for a 2-row, 1-column (that is, one atop the other) layout. You need to ask for a 1-row, 2-column layout instead. When you do, the result will be:

您目前要求 2 行 1 列(即一个在另一个之上)布局。您需要改为要求 1 行 2 列布局。当你这样做时,结果将是:

side by side plot

并排情节

In order to minimize the overlap of subplots, you might want to kick in a:

为了最大限度地减少子图的重叠,您可能需要启动:

plt.tight_layout()

before the show. Yielding:

演出前。产量:

neater side by side plot

更整洁的并排图

回答by busybear

Check this page out: http://matplotlib.org/examples/pylab_examples/subplots_demo.html

查看此页面:http: //matplotlib.org/examples/pylab_examples/subplots_demo.html

plt.subplotsis similar. I think it's better since it's easier to set parameters of the figure. The first two arguments define the layout (in your case 1 row, 2 columns), and other parameters change features such as figure size:

plt.subplots类似。我认为它更好,因为设置图形参数更容易。前两个参数定义布局(在您的情况下为 1 行 2 列),其他参数用于更改图形大小等功能:

import numpy as np
import matplotlib.pyplot as plt

x1 = np.linspace(0.0, 5.0)
x2 = np.linspace(0.0, 2.0)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
y2 = np.cos(2 * np.pi * x2)

fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(5, 3))
axes[0].plot(x1, y1)
axes[1].plot(x2, y2)
fig.tight_layout()

enter image description here

在此处输入图片说明