Home > Back-end >  Is it possible to extract the default tick locations from the primary axis and pass it to a secondar
Is it possible to extract the default tick locations from the primary axis and pass it to a secondar

Time:10-31

When making a plot with with

        fig, ax = plt.subplots()
        x=[1,2,3,4,5,6,7,8,9,10]
        y=[1,2,3,4,5,6,7,8,9,10]
        ax.plot(x,y)
        plt.show()

matplotlib will determine the tick spacing/location and value of the tick. Is there are way to extract this automatic spacing/location AND the value? I want to do this so i can pass it to

set_xticks()

for my secondary axis (using twiny()) then use set_ticklabels() with a custom label. I realise I could use secondary axes giving both a forward and inverse function however providing an inverse function is not feasible for the goal of my code.

So in the image below, the ticks are only showing at 2,4,6,8,10 rather than all the values of x and I want to somehow extract these values and position so I can pass to set_xticks() and then change the tick labels (on a second x axis created with twiny).

enter image description here

CodePudding user response:

# From "get_xticks" Doc: The locations are not clipped to the current axis limits 
# and hence may contain locations that are not visible in the output.
current_x_ticks = ax.get_xticks()

current_x_limits = ax.get_xlim()
ax.set_yticks(current_x_ticks) # Use this before "set_ylim"
ax.set_ylim(current_x_limits)    

plt.show()
  • Related