Reputation: 271
I'm trying to plot a graph with two y-axis, and I saw a question here related to that which I tried to follow. However, it still doesn't seem to work. Any idea how to fix this?
import numpy as np
import matplotlib.pyplot as plt
t = np.array([0,1])
data1 = np.array([5, 6])
data2 = np.array([2.5, 3.0])
fig, ax1 = plt.subplots()
my_xticks = ['March','April']
color = 'tab:red'
ax1.set_xlabel('Month')
ax1.set_ylabel('Mio', color=color)
ax1.plot(t, data1, color=color)
ax1.tick_params(axis='y', labelcolor=color)
ax2 = ax1.twinx()
color = 'tab:blue'
ax2.set_ylabel('sin', color=color) # we already handled the x-label with ax1
ax2.plot(t, data2, color=color)
ax2.tick_params(axis='y', labelcolor=color)
fig.tight_layout() # otherwise the right y-label is slightly clipped
plt.xticks(t, my_xticks)
plt.show()
This gives me as output only one line
Upvotes: 0
Views: 138
Reputation: 308
it is plotting two lines! It just so happens with these axis that they overlap! If you change the number in the arrays you will see. I spent some time looking at this one before I spotted what was going on! Here is my example that uncovered it:
t = np.array([0,1,3])
data1 = np.array([5, 6,8])
data2 = np.array([2.5, 3.0,8])
fig, ax1 = plt.subplots()
my_xticks = ['March','April','May']
EDIT: To solve this problem without more data points you need to set the y-axis values.
import numpy as np
import matplotlib.pyplot as plt
t = np.array([0,1])
data1 = np.array([5, 6])
data2 = np.array([2.5, 3.0])
fig, ax1 = plt.subplots()
my_xticks = ['March','April','May']
color = 'tab:red'
ax1.set_xlabel('Month')
ax1.set_ylabel('Mio', color=color)
ax1.plot(t, data1, color=color)
ax1.tick_params(axis='y', labelcolor=color)
plt.ylim(0,8)#####here is the money maker
ax2 = ax1.twinx()
color = 'tab:blue'
ax2.set_ylabel('sin', color=color) # we already handled the x-label with ax1
ax2.plot(t, data2, color=color)
ax2.tick_params(axis='y', labelcolor=color,length=5)
plt.ylim(0,8)#####here is the money maker
fig.tight_layout() # otherwise the right y-label is slightly clipped
plt.xticks(t, my_xticks)
plt.show()
Upvotes: 1