How to get pixel coordinates for Matplotlib-generated scatterplot?

前端 未结 2 1173
悲&欢浪女
悲&欢浪女 2020-12-03 04:19

I use Matplotlib to generate PNG files of scatterplots. Now, for each scatterplot, in addition to a PNG file, I would also like to generate a list of pixel coordin

相关标签:
2条回答
  • 2020-12-03 04:43

    Doing this is fairly simple, but to understand what's going on, you'll need to read up a bit on matplotlib's transforms. The transformations tutorial is a good place to start.

    At any rate, here's an example:

    import numpy as np
    import matplotlib.pyplot as plt
    
    fig, ax = plt.subplots()
    points, = ax.plot(range(10), 'ro')
    ax.axis([-1, 10, -1, 10])
    
    # Get the x and y data and transform it into pixel coordinates
    x, y = points.get_data()
    xy_pixels = ax.transData.transform(np.vstack([x,y]).T)
    xpix, ypix = xy_pixels.T
    
    # In matplotlib, 0,0 is the lower left corner, whereas it's usually the upper 
    # left for most image software, so we'll flip the y-coords...
    width, height = fig.canvas.get_width_height()
    ypix = height - ypix
    
    print 'Coordinates of the points in pixel coordinates...'
    for xp, yp in zip(xpix, ypix):
        print '{x:0.2f}\t{y:0.2f}'.format(x=xp, y=yp)
    
    # We have to be sure to save the figure with it's current DPI
    # (savfig overrides the DPI of the figure, by default)
    fig.savefig('test.png', dpi=fig.dpi)
    

    This yields:

    Coordinates of the points in pixel coordinates...
    125.09  397.09
    170.18  362.18
    215.27  327.27
    260.36  292.36
    305.45  257.45
    350.55  222.55
    395.64  187.64
    440.73  152.73
    485.82  117.82
    530.91  82.91
    

    enter image description here

    0 讨论(0)
  • 2020-12-03 04:45

    Try annotation box : http://matplotlib.org/examples/pylab_examples/demo_annotation_box.html

    import matplotlib.pyplot as plt
    from matplotlib.offsetbox import TextArea, DrawingArea, OffsetImage, \
         AnnotationBbox
    
    for (x, y), m, c in zip(points, markers, colors):
        ax.scatter(x, y, marker=m, c=c, s=SIZE, vmin=VMIN, vmax=VMAX)
    
        for px, py in zip(x,y):
            offsetbox = TextArea( " %s, %s" (px, py ) , minimumdescent=False)
            ab = AnnotationBbox(offsetbox,(px, py ),
                            xybox=(-20, 40),
                            xycoords='data',
                            boxcoords="offset points",
                            arrowprops=dict(arrowstyle="->"))
            ax.add_artist(ab)
    

    I don't have matplotlib installed on my current computer, so my code might not work.

    0 讨论(0)
提交回复
热议问题