Matplotlib-y轴的双刻度距离不匹配

时间:2019-09-07 19:18:19

标签: matplotlib plot

我正在尝试创建带有两个y轴的图。右边的刻度应该是左边的刻度的两倍,我希望它们的距离相等。因此,如果左y轴说10,我希望20在右边的高度完全相同。

到目前为止,他们几乎相匹配,但是规模越大,我们开始发现一些差异。对于最后三个标签,这一点尤其明显(例如180略低于90)。

两个轴的刻度数相同。它们都共享相同的x范围,但具有不同的值。

这是情节现在的样子:

enter image description here https://imgur.com/a/22eQvMw

这是带有一些示例数据的绘图代码:

times = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]
delay_values = [0.0, 10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0, 90.0]
ping_times = [0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5]
rtt_averages = [1.823, 23.589, 44.632, 67.288, 86.011, 105.972, 124.518, 147.082, 165.398, 183.723]

# plot
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
lns1 = ax1.step(times, delay_values, '-rx', label='Artificial Delay', where='post')
lns2 = ax2.plot(ping_times, rtt_averages, 'bo', label='Ping Round Trip Time (RTT)')
plt.title("Echo Request/Reply after Adding Artificial Delay")

# axis labels
ax1.set_ylabel('Artificial Delay (ms)', color='r')
ax1.set_xlabel("Time (seconds)")
ax1.tick_params(axis='y', colors='red')

ax2.set_ylabel('Ping Round Tript Time RTT (ms)', color='b')
ax2.tick_params(axis='y', colors='blue')

# legend
lns = lns1+lns2
labs = [l.get_label() for l in lns]
plt.legend(lns, labs, loc=0)

# scale ticks
# right y scale tick values
plt.yticks(np.arange(0, max(rtt_averages), 20))
# left y scale values
ax1.set_yticks(np.arange(min(delay_values), max(delay_values)+10, 10))
# x scale tick values
ax1.xaxis.set_ticks(np.arange(0, 11, 1))

fig.tight_layout()
plt.show()

我期望的结果是,右侧y轴的刻度线与左侧的刻度线高度相同。由于我是Matplotlib的新手,所以我不确定问题出在哪里。

任何帮助将不胜感激!

谢谢!

0 个答案:

没有答案
相关问题