tommy.carstensen
tommy.carstensen

Reputation: 9622

matplotlib 2nd axis label not showing

With matplotlib how can I get a 2nd y-axis label to show? This is what I have tried:

import matplotlib.pyplot as plt
x = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.65]
y = [0, 0.15, 0.3, 0.35, 0.4, 0.55, 0.57, 0.58]
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twinx().twiny()
ax2.set_xlabel('2nd x-axis label')
ax2.set_ylabel('2nd y-axis label')
ax1.set_xlim([0,1])
ax1.plot(x, y)
plt.show()

enter image description here

Upvotes: 2

Views: 3516

Answers (1)

BrenBarn
BrenBarn

Reputation: 251408

twinx and twiny actually create separate axes objects. Since you set ax2 = ax1.twinx().twiny() you are only "saving" the result of the twiny call, not the twinx call. You need to set the x and y labels separately on the two axes, which means you need to save the twinx axes for later access:

import matplotlib.pyplot as plt
x = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.65]
y = [0, 0.15, 0.3, 0.35, 0.4, 0.55, 0.57, 0.58]
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twinx()
ax3 = ax2.twiny()
ax3.set_xlabel('2nd x-axis label')
ax2.set_ylabel('2nd y-axis label')
ax1.set_xlim([0,1])
ax1.plot(x, y)

Upvotes: 3

Related Questions