如何使用自定义标记与情节?

tpu*_*nen 15 matplotlib

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

Mar*_*ark 26

我不相信matplotlib可以自定义这样的标记.请参阅此处了解自定义级别,该级别远远低于您的需求.

作为替代方案,我编写了这个使用figimage将图像放置在线点位置的kludge.

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

# constants
dpi = 72; imageSize = (32,32)
# read in our png file
im = image.imread('smile.png')

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.get_frame().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()
Run Code Online (Sandbox Code Playgroud)

生产:

在此输入图像描述

  • AttributeError:'AxesSubplot'对象没有属性'get_frame' (2认同)

小智 7

接下来是Mark的回答.我只是想我会添加一点,因为我试图运行它,它做了我想要的,除了实际显示图形上的图标.也许matplotlib发生了一些变化.它已经连续4年.

代码行:

ax.get_frame().set_alpha(0)
Run Code Online (Sandbox Code Playgroud)

但是,它似乎不起作用

ax.patch.set_alpha(0)
Run Code Online (Sandbox Code Playgroud)

确实有效.


Imp*_*est 6

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

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()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明