Python 如何在绘图时使用自定义png图像标记?

Python 如何在绘图时使用自定义png图像标记?,python,matplotlib,Python,Matplotlib,我想在散点图和折线图中使用客户标记。如何从PNG文件中创建自定义标记?我不相信matplotlib可以自定义这样的标记。有关自定义级别的信息,请参见,这远远低于您的需要 作为替代方案,我编写了这个乱七八糟的代码,它使用figimage将图像放置在直线点位置 import matplotlib.pyplot as plt import matplotlib.image as image # constant dpi = 72 # read in our png file im = image.i

我想在散点图和折线图中使用客户标记。如何从PNG文件中创建自定义标记?

我不相信matplotlib可以自定义这样的标记。有关自定义级别的信息,请参见,这远远低于您的需要

作为替代方案,我编写了这个乱七八糟的代码,它使用figimage将图像放置在直线点位置

import matplotlib.pyplot as plt
import matplotlib.image as image

# constant
dpi = 72
# read in our png file
im = image.imread('smile.png')
image_size = im.shape[1], im.shape[0]

fig = plt.figure(dpi=dpi)
ax = fig.add_subplot(111)
# plot our line with transparent markers, and markersize the size of our image
line, = ax.plot((1,2,3,4),(1,2,3,4),"bo",mfc="None",mec="None",markersize=imageSize[0] * (dpi/ 96))
# we need to make the frame transparent so the image can be seen
# only in trunk can you put the image on top of the plot, see this link:
# http://www.mail-archive.com/matplotlib-users@lists.sourceforge.net/msg14534.html
ax.patch.set_alpha(0)
ax.set_xlim((0,5))
ax.set_ylim((0,5))

# translate point positions to pixel positions
# figimage needs pixels not points
line._transform_path()
path, affine = line._transformed_path.get_transformed_points_and_affine()
path = affine.transform_path(path)
for pixelPoint in path.vertices:
    # place image at point, centering it
    fig.figimage(im,pixelPoint[0]-imageSize[0]/2,pixelPoint[1]-imageSize[1]/2,origin="upper")

plt.show()
产生:


根据马克的回答。我只是想我会增加一点,因为我试着运行它,它做我想要的,除了在图表上实际显示图标。也许matplotlib发生了一些变化。已经四年了

一行代码,内容如下:

ax.get_frame().set_alpha(0)
然而,这似乎不起作用

ax.patch.set_alpha(0)

确实有效。

另一个答案可能会导致调整图形大小时出现问题。这里有一种不同的方法,将图像定位在注释框内,注释框固定在数据坐标中

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()

AttributeError:'AxeSubPlot'对象没有属性'get_frame',有关处理get_frame错误的信息,请参见t gillespie的回答。我建议将其标记为以下内容的副本:代替png图像,可以检查是否存在包含适当符号的字体集,该符号可以用作标记。任何一种都可以使用标准的utf8符号,如中所示,或者如果需要特定的字体,例如中所示。