Search code examples
pythonmatplotlib

How do I get the coordinates of plotted points in a matplotlib plot with a non-numerical axis


I have a line plot with a numerical y-axis and strings on the x-axis built using a dataframe: plot

I want to find the actual coordinates of each of those plotted points. I want those coordinates so I can know where to place annotations, and I want to place them as labels at the middle of each line (its midpoint) and offset them according to the line's slope.

I've tried using line.get_data() but that just gives me the string value for x again. If this isn't possible, is there another way for me to know where to place my annotations?


Solution

  • This can be done with the orig parameter to get_xdata:

    import matplotlib.pyplot as plt
    
    fig, ax = plt.subplots()
    line, = ax.plot(['a', 'b', 'c'], [1, 2, 3])
    
    print(line.get_xdata(orig=False))
    

    Output:

    [0. 1. 2.]