Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Controlling the tracker when using twinx

enter image description here

The tracker in the lower-right corner (highlighted 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')
like image 852
unutbu Avatar asked Oct 05 '11 12:10

unutbu


2 Answers

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.

enter image description here

like image 102
unutbu Avatar answered Nov 16 '22 08:11

unutbu


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()
like image 38
fischanger Avatar answered Nov 16 '22 08:11

fischanger