我试图绘制一个带有两个y轴的图形,我在这里看到了一个与我试图遵循的问题相关的问题。但是,它似乎仍然不起作用。知道如何解决这个问题吗?
import numpy as np
import matplotlib.pyplot as plt
t = np.array([0,1])
data1 = np.array([5, 6])
data2 = np.array([2.5, 3.0])
fig, ax1 = plt.subplots()
my_xticks = ['March','April']
color = 'tab:red'
ax1.set_xlabel('Month')
ax1.set_ylabel('Mio', color=color)
ax1.plot(t, data1, color=color)
ax1.tick_params(axis='y', labelcolor=color)
ax2 = ax1.twinx()
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)
fig.tight_layout() # otherwise the right y-label is slightly clipped
plt.xticks(t, my_xticks)
plt.show()
这使我只输出一行
它正在绘制两条线!它们恰好与这些轴重叠,它们重叠!如果更改阵列中的数字,您将看到。在我发现发生了什么之前,我花了一些时间看这个!这是我揭示它的例子:
t = np.array([0,1,3])
data1 = np.array([5, 6,8])
data2 = np.array([2.5, 3.0,8])
fig, ax1 = plt.subplots()
my_xticks = ['March','April','May']
编辑:要在没有更多数据点的情况下解决此问题,您需要设置y轴值。
import numpy as np
import matplotlib.pyplot as plt
t = np.array([0,1])
data1 = np.array([5, 6])
data2 = np.array([2.5, 3.0])
fig, ax1 = plt.subplots()
my_xticks = ['March','April','May']
color = 'tab:red'
ax1.set_xlabel('Month')
ax1.set_ylabel('Mio', color=color)
ax1.plot(t, data1, color=color)
ax1.tick_params(axis='y', labelcolor=color)
plt.ylim(0,8)#####here is the money maker
ax2 = ax1.twinx()
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,length=5)
plt.ylim(0,8)#####here is the money maker
fig.tight_layout() # otherwise the right y-label is slightly clipped
plt.xticks(t, my_xticks)
plt.show()