我正在尝试绘制一个具有两个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()
这使我仅输出一行
答案 0 :(得分:1)
正在绘制两条线!这些轴恰好发生重叠。如果您更改数组中的数字,将会看到。我花了一些时间看这个,然后才发现发生了什么!这是我发现的示例:
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()