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

2024-04-24 09:57:02 发布

您现在位置:Python中文网/ 问答频道 /正文

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


Tags: 文件标记客户png折线图
3条回答

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

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

enter image description here

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

作为替代,我已经编写了这个乱码,它使用matplotlib.image将图像放置在线点位置

import matplotlib.pyplot as plt
from matplotlib import image

# constant
dpi = 72
path = 'smile.png'
# read in our png file
im = image.imread(path)
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=image_size[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]-image_size[0]/2,pixelPoint[1]-image_size[1]/2,origin="upper")

plt.show()

产生:

enter image description here

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

一行代码,内容如下:

ax.get_frame().set_alpha(0)

然而,这似乎不起作用

ax.patch.set_alpha(0)

确实有效

相关问题 更多 >