【发布时间】:2021-03-12 11:22:02
【问题描述】:
我有两个图,但绘制在同一个 x 轴上。我想将两个图彼此相邻(并排)绘制,而不是垂直绘制。 我该怎么做?
从 matplotlib 文档中借用的示例数据。我试过了,我将第一个图放到 plt.subplots 中,但第二个图仍然绘制在下面而不是在第一个图旁边:
import numpy as np
import matplotlib.pyplot as plt
# Create some mock data
t = np.arange(0.01, 10.0, 0.01)
data1 = np.exp(t)
data2 = np.sin(2 * np.pi * t)
## initiating the plots next to each other
fig,(ax1,ax2) = plt.subplots(1,2)
color = 'tab:red'
ax1.set_xlabel('time (s)')
ax1.set_ylabel('exp', color=color)
ax1.plot(t, data1, color=color)
ax1.tick_params(axis='y', labelcolor=color)
ax2 = ax1.twinx() # instantiate a second axes that shares the same x-axis
color = 'tab:blue'
ax2.set_ylabel('sin', color=color) # we already handled the x-label with ax1
ax2.plot(t, data2, color=color)
ax2.tick_params(axis='y', labelcolor=color)
plt.xlim(0,4)
fig.tight_layout() # otherwise the right y-label is slightly clipped
plt.show()
fig, ax1 = plt.subplots()
color = 'tab:red'
ax1.set_xlabel('time (s)')
ax1.set_ylabel('exp', color=color)
ax1.plot(t, data1, color=color)
ax1.tick_params(axis='y', labelcolor=color)
ax2 = ax1.twinx() # instantiate a second axes that shares the same x-axis
color = 'tab:blue'
ax2.set_ylabel('sin', color=color) # we already handled the x-label with ax1
ax2.plot(t, data2, color=color)
ax2.tick_params(axis='y', labelcolor=color)
plt.xlim(4,6)
fig.tight_layout() # otherwise the right y-label is slightly clipped
plt.show()
【问题讨论】:
标签: python numpy matplotlib jupyter