开发者

Controlling the tracker when using twinx

开发者 https://www.devze.com 2023-04-11 02:25 出处:网络
The tracker in the lower-right corner (h开发者_如何转开发ighlighted in red) reports y-values relative to the y-axis on the right.

Controlling the tracker when using twinx

The tracker in the lower-right corner (h开发者_如何转开发ighlighted in red) reports y-values relative to the y-axis on the right.

How can I get the tracker to report y-values relative to the y-axis on the left instead?

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()

I know swapping y1 with y2 will make the tracker report y1-values, but this also places the y1 tickmarks on the right-hand side, which is not what I want to happen.

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


Ah, found it: ax.yaxis.set_ticks_position("right"). Instead of trying to "control the tracker", you can swap the location of the y-axes.

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, the tracker always follows ax2 when using twinx.

Controlling the tracker when using twinx


Please note that if you create an ax3= ax1.twiny() axes after ax1 and ax2, the tracker goes to ax3 and you have again it reporting y1 values.

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()
0

精彩评论

暂无评论...
验证码 换一张
取 消