我想在散点图和折线图中使用客户标记。如何从PNG文件中制作自定义标记?
答案 0 :(得分:25)
我不相信matplotlib可以自定义这样的标记。有关自定义级别的信息,请参阅here。
作为替代方案,我编写了这个使用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()
产地:
答案 1 :(得分:5)
继Mark的回答之后。我只是想我会添加一点,因为我试图运行它,它做了我想要的,除了实际显示图形上的图标。也许matplotlib发生了一些变化。 已经已经4年了。
代码行:
ax.get_frame().set_alpha(0)
似乎不起作用,但是
ax.patch.set_alpha(0)
确实有效。
答案 2 :(得分:2)
调整数字大小时,其他答案可能会导致问题。这是另一种方法,将图像定位在锚定在数据坐标中的注释框中。
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()