Reputation: 3048
I want to create a secondary xaxis at the top which has an inverse relation with the major xaxis at the bottom. I followed the official tutorial here and have the following codes:
def forward(x):
return 10/x
def backward(y):
return 10/y
fig, ax = plt.subplots()
ax.set_xlim([0.14, 1.4])
secax = ax.secondary_xaxis('top', functions=(forward, backward))
secax.set_xticks(np.array([10,20,40,70])) # does not work!
plt.show()
The problem is that the xticks at the top are not at the right place. They are bunched together in the left due to the inverse function applied. How do I manually set the position of the xticks? (e.g. at 10,20,40,70)
Edit:
Just to make it more clear, the ticks are at the right place, but there are too many tickss as shown in the figure. In this case, I only want the ticks at 10, 20, 40, 70 (I don't want the ticks at 30, 50 and 60 as we can't see all the tick numbers clearly)
Upvotes: 5
Views: 3822
Reputation: 730
I believe either you missed import statement for numpy or you need to update you matplotlib. Below works fine for me -
import matplotlib.pyplot as plt
import numpy as np
def forward(x):
return 10/x
def backward(y):
return 10/y
fig, ax = plt.subplots()
ax.set_xlim([0.14, 1.4])
secax = ax.secondary_xaxis('top', functions=(forward, backward))
secax.set_xticks(np.array([10,20,40,70])) # does not work!
plt.show()
Check your version -
import matplotlib
print (matplotlib.__version__)
If above doesn't print 3.2.1. try below -
pip install matplotlib==3.2.1
Upvotes: 3
Reputation: 4547
It is not clear what you want to achieve.
If you want a linear relationship at the top, this might be relevant:
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
ax.set_xlim([0.14, 1.4])
secax = ax.secondary_xaxis('top', functions=(lambda x: 77 - 50 * x,
lambda y: (77 - y) / 50))
secax.set_xticks(np.array([10, 20, 40, 70]))
plt.show()
Upvotes: 0