Search code examples
pythonmatplotlibalignment

Is it possible to draw xticklabels on top of the xaxis?


I want to mark a specific x-axis position with a colored asterisk drawn on top of the x-axis.

I use an x-tick label as the marker (because I couldn't figure out if it is possible to place markers anywhere in the fig coords) at it's aligned properly but is drawn below the x-axis so it's partially covered.

MWE:

import numpy as np
import matplotlib.pyplot as plt

fig,ax=plt.subplots(1,1)

ax.scatter([-1,1],[1,1])
ax.set_xticks([0],minor=True)
ax.set_xticklabels(['*'],minor=True,color='r',fontsize=20,verticalalignment='center')

plt.setp(ax.spines.values(), linewidth=3)

plt.show()

That's what it looks like right now:

enter image description here


Solution

  • You can specify the coordinates of a scatter in a blended system (data coordinates for the y axis and axis coordinates for the x axis).
    To then have the scatter marker above the spines set the zorder property of the scatter to something above 2.5.

    import matplotlib.pyplot as plt
    
    fig,ax=plt.subplots(1,1)
    
    ax.scatter([-1,1],[1,1])
    ax.scatter(0,0, s=100, marker="*", color="red", 
               transform=ax.get_xaxis_transform(), clip_on=False, zorder=3)
    
    plt.show()
    

    enter image description here