如何使用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屋!