使用twinx时控制跟踪器

时间:2011-10-05 12:00:18

标签: python matplotlib

enter image description here

右下角的跟踪器(以红色突出显示)报告右侧相对于y轴的y值。

如何让跟踪器报告相对于左侧y轴的y值呢?

import matplotlib.pyplot as plt
import numpy as np

np.random.seed(6)
numdata = 100
t = np.linspace(0.05, 0.11, numdata)
y1 = np.cumsum(np.random.random(numdata) - 0.5) * 40000
y2 = np.cumsum(np.random.random(numdata) - 0.5) * 0.002

fig = plt.figure()

ax1 = fig.add_subplot(111)
ax2 = ax1.twinx()

ax1.plot(t, y1, 'r-', label='y1')
ax2.plot(t, y2, 'g-', label='y2')

ax1.legend()
plt.show()

我知道用y1交换y2会使跟踪器报告y1值, 但这也将y1标记放在右侧,这不是我想要发生的。

ax1.plot(t, y2, 'g-', label='y2')
ax2.plot(t, y1, 'r-', label='y1')

2 个答案:

答案 0 :(得分:3)

啊,发现它:ax.yaxis.set_ticks_position("right")。 您可以交换y轴的位置,而不是试图“控制跟踪器”。

ax1.yaxis.set_ticks_position("right")
ax2.yaxis.set_ticks_position("left")

ax1.plot(t, y2, 'g-', label='y1')
ax2.plot(t, y1, 'r-', label='y2')

AFAIK,使用ax2时跟踪器始终跟随twinx

enter image description here

答案 1 :(得分:3)

请注意,如果您在ax1和ax2之后创建ax3= ax1.twiny()轴,则跟踪器会转到ax3,您再次报告y1值。

import matplotlib.pyplot as plt
import numpy as np

np.random.seed(6)
numdata = 100
t = np.linspace(0.05, 0.11, numdata)
y1 = np.cumsum(np.random.random(numdata) - 0.5) * 40000
y2 = np.cumsum(np.random.random(numdata) - 0.5) * 0.002

fig = plt.figure()

ax1 = fig.add_subplot(111)
ax2 = ax1.twinx()

ax1.plot(t, y1, 'r-', label='y1')
ax2.plot(t, y2, 'g-', label='y2')

ax1.legend()
ax3 = ax1.twiny()
ax3.set_xticks([])
plt.show()