如何使用 Python 并排绘制两个图? [英] How to make two plots side-by-side using Python?
问题描述
我在 matplotlib 上找到了以下示例:
I found the following example on 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?
推荐答案
将子图设置更改为:
plt.subplot(1, 2, 1)
...
plt.subplot(1, 2, 2)
subplot
的参数是:行数、列数以及您当前所在的子图.所以 1, 2, 1
的意思是一个 1 行 2 列的图形:转到第一个子图."然后 1, 2, 2
表示一个 1 行 2 列的图形:转到第二个子图."
The parameters for subplot
are: number of rows, number of columns, and which subplot you're currently on. So 1, 2, 1
means "a 1-row, 2-column figure: go to the first subplot." Then 1, 2, 2
means "a 1-row, 2-column figure: go to the second subplot."
您目前要求采用 2 行 1 列(即一个在另一个之上)的布局.您需要改为要求 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:
为了尽量减少子图的重叠,您可能需要加入:
In order to minimize the overlap of subplots, you might want to kick in a:
plt.tight_layout()
演出前.产量:
这篇关于如何使用 Python 并排绘制两个图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!