python-3.xmatplotlibaxes

Is it possible to extract the default tick locations from the primary axis and pass it to a secondary access with matplotlib?


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

UPDATE

When using the fix suggested it works well for the x axis. However, it does not work well for the y-axis. For the y-axis it seems to take the dataset values for the y ticks only. My code is:


ax4 = ax.twinx()
ax4.yaxis.set_ticks_position('left')
ax4.yaxis.set_label_position('left') 
ax4.spines["left"].set_position(("axes", -0.10))
ax4.set_ylabel(self.y_2ndary_label, fontweight = 'bold')
Y = ax.get_yticks()
ax4.yaxis.set_ticks(Y)
ax4.yaxis.set_ticklabels( Y*Y )
ax4.set_ylim(ax.get_ylim())
          
fig.set_size_inches(8, 8)
plt.show()

but this gives me the following plot. The plot after is the original Y axis. This is not the case when I do this on the x-axis. Any ideas?

enter image description here

enter image description here


Solution

  • # 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()