How to use custom png image marker with plot?

后端 未结 3 2064
隐瞒了意图╮
隐瞒了意图╮ 2020-11-27 19:05

I would like to utilize customer markers in both scatter and line charts. How can I make custom marker out of a PNG file?

3条回答
  •  没有蜡笔的小新
    2020-11-27 19:33

    The other answer may lead to problems when resizing the figure. Here is a different approach, positionning the images inside annotation boxes, which are anchored in data coordinates.

    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib.offsetbox import OffsetImage, AnnotationBbox
    
    path = "https://upload.wikimedia.org/wikipedia/commons/b/b5/Tango-example_icons.png"
    image = plt.imread(path)[116:116+30, 236:236+30]
    
    x = np.arange(10)
    y = np.random.rand(10)
    
    fig, ax = plt.subplots()
    ax.plot(x,y)
    
    def plot_images(x, y, image, ax=None):
        ax = ax or plt.gca()
    
        for xi, yi in zip(x,y):
            im = OffsetImage(image, zoom=72/ax.figure.dpi)
            im.image.axes = ax
    
            ab = AnnotationBbox(im, (xi,yi), frameon=False, pad=0.0,)
    
            ax.add_artist(ab)
    
    plot_images(x, y, image, ax=ax)
    
    plt.show()
    

提交回复
热议问题