import matplotlib.pyplot as plt
import numpy as np
## Create a figure and a set of subplots.
## 1 row, 2 columns.
fig, (ax1, ax2) = plt.subplots(1, 2)
## Save the figure to a file.
## The file will be created in the /home/labex/project directory.
plt.savefig('plot1.png')
print("Figure saved as plot1.png")
import matplotlib.pyplot as plt
import numpy as np
## Create some data
x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x ** 2)
## Create a figure and a set of subplots
fig, (ax1, ax2) = plt.subplots(1, 2)
## Plot on the first subplot (ax1)
ax1.plot(x, y)
ax1.set_title('Sine Wave')
## Save the figure to a new file
plt.savefig('plot2.png')
print("Figure saved as plot2.png")
import matplotlib.pyplot as plt
import numpy as np
## Create some data
x = np.linspace(0, 2 * np.pi, 400)
y1 = np.sin(x ** 2)
y2 = np.cos(x ** 2)
## Create a figure and a set of subplots
fig, (ax1, ax2) = plt.subplots(1, 2)
## Plot on the first subplot (ax1)
ax1.plot(x, y1)
ax1.set_title('Sine Wave')
## Plot on the second subplot (ax2)
ax2.plot(x, y2, 'tab:orange')
ax2.set_title('Cosine Wave')
## Save the figure to a new file
plt.savefig('plot3.png')
print("Figure saved as plot3.png")
import matplotlib.pyplot as plt
import numpy as np
## Create some data
x = np.linspace(0, 2 * np.pi, 400)
y1 = np.sin(x ** 2)
y2 = np.cos(x ** 2)
## Create a figure and a set of subplots
fig, (ax1, ax2) = plt.subplots(1, 2)
## Plot on the first subplot (ax1)
ax1.plot(x, y1)
ax1.set_title('Sine Wave')
## Plot on the second subplot (ax2)
ax2.plot(x, y2, 'tab:orange')
ax2.set_title('Cosine Wave')
## Adjust layout to prevent overlap
plt.tight_layout()
## Save the figure to a new file
plt.savefig('plot4.png')
print("Figure saved as plot4.png")
为了演示这一点,让我们创建一个新脚本。在你的项目目录中创建一个名为 shared_axes.py 的文件,并添加以下代码。此示例将创建两个垂直堆叠的子图(nrows=2, ncols=1),它们共享相同的 x 轴。
import matplotlib.pyplot as plt
import numpy as np
## Create data
t = np.arange(0.01, 5.0, 0.01)
s1 = np.exp(t)
s2 = np.sin(2 * np.pi * t)
## Create a figure and two subplots that share the x-axis
fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True)
## Plot on the first subplot
ax1.plot(t, s1, 'tab:blue')
ax1.set_ylabel('Exponential')
## Plot on the second subplot
ax2.plot(t, s2, 'tab:orange')
ax2.set_ylabel('Sinusoidal')
ax2.set_xlabel('time (s)')
## Adjust layout
plt.tight_layout()
## Save the figure
plt.savefig('plot5.png')
print("Figure saved as plot5.png")
现在,从终端运行这个新脚本。
python3 shared_axes.py
输出:
Figure saved as plot5.png
打开 plot5.png。请注意,x 轴刻度标签仅显示在底部子图(ax2)上。这是因为 sharex=True 会自动隐藏内部的 x 轴标签,以获得更整洁的外观。两个图表在 x 轴上完美对齐,便于比较。