Reputation: 870
Pardon my poor python skills, I am rather new to the language!
None the less, I am confused by the results I am getting from twinx()
currently. I am not sure why when I twin the x axis, the ticks on the right hand side y axis seem to double.
import matplotlib.pyplot as plt
x = linspace(0,2*pi,100)
y = sin(x) + 100*rand(len(x))
z = cos(x) + 100*rand(len(x))
data = []
data.append(y)
data.append(z)
fig = plt.figure(1)
for kk in range(len(data)):
ax1 = fig.add_subplot(111)
ax1.plot(x.T, data[kk], 'b.-')
plt.show()
The first plot displays (to my mind) the correct behavior
fig2 = plt.figure(2)
for kk in range(len(data)):
ax3 = fig2.add_subplot(111)
ax4 = ax3.twinx()
ax4.plot(x.T, data[kk], 'b.-')
plt.show()
While the second plot (where all I have done is flip the axis) seems to have poor y tick behavior wherein the two 'curves' each get their own tick marks.
Any thoughts as to why this might be occurring would be greatly appreciated!
Upvotes: 3
Views: 5793
Reputation: 21
If you take the call to twinx()
and add_subplot()
out of the loop, I think you'll get the figure you're after. Like so:
fig2 = plt.figure(2)
ax3 = fig2.add_subplot(111)
ax4 = ax3.twinx()
for kk in range(len(data)):
ax4.plot(x.T, data[kk], 'b.-')
plt.show()
By the end of your loop you're calling twinx()
twice, so you naturally get two twinned axes. Since they have different scales, the numbers overlap in an awkward way.
Upvotes: 2
Reputation: 284562
Because that's what twinx
is supposed to do :)
Seriously, though, the point of twinx
is to create an independent y-axis on the same plot. By default, it shows the ticks for the second, independent y-axis on the right hand side of the plot.
The idea is that you can do something like this using twinx
(or twiny
if you want two independent x-axes):
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
ax2 = ax.twinx()
x = np.linspace(0, 10, 100)
ax.plot(x, np.sin(x), color='blue')
ax.set_ylabel(ylabel='Y-Value 1', color='blue')
ax.set_xlabel('Same X-values')
ax2.plot(x, x**3, color='green')
ax2.set_ylabel('Y-Value 2', color='green')
plt.show()
If you just want two curves that share the same axes, just plot them on the same axes. E.g.:
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
x = np.linspace(0, 10, 100)
ax.plot(x, x, label='$y=x$')
ax.plot(x, 3 * x, label='$y=3x$')
ax.legend(loc='upper left')
ax.set(xlabel='Same X-values', ylabel='Same Y-values')
plt.show()
Upvotes: 2