Search code examples
pythonmatplotlibaxes

how can I plot on the axes


I actually want to recreate an image like the following: enter image description here

Specially the little X on the xaxes I have a

list = [[100,-3],[200,None],[120,-2] ... ]

and I do

for x in list:
     if x[1]!=None:
          plot(x[0],x[1],'ok')
     else:
          ###  PLot on the axes ###

But while I am plotting I do not know what the axes are. I know that some values are None, for example ( 250,None), So I want to plot on the xaxes at x = 250, but I have not idea what eventually the min(ylim()) will be.

I know I can do plot(250,-5,'X',zorder=999999) but this is only when I know what the min axes is.. (I can not do min, max and so to know the min axes. as the real data is a list inside a list inside a dictionary etc.. )


Solution

  • So the trick is to use a custom transformation. The regular data transformation for the x axis and the axes transformation for the y axis. Matplotlib calls that a blended transformation, which you need to create yourself. You'll find more information in this awesome guide.

    And as @ThePredator already pointed out, you have to set clip_on=False, otherwise your markers will be clipped.

    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.transforms as transforms
    
    fig, ax = plt.subplots()
    
    # the x coords of this transformation are data, and the
    # y coord are axes
    trans = transforms.blended_transform_factory( ax.transData, ax.transAxes)
    
    # data points on the axes
    x = np.random.rand(5)*100. + 200.
    y = [0]*5
    ax.plot(x, y, 'kx', transform=trans, markersize=10, markeredgewidth=2,
            clip_on=False)
    
    # regular data
    x = np.random.rand(5)*100. + 200.
    y = np.random.rand(5)*100. + 200.
    ax.plot(x, y, 'ro')
    
    plt.show()
    

    Result:

    enter image description here