有很多关于将预先保存的PNG图像绘制为散点绘图标记的帖子,但我想知道是否有一种方法可以获取2D数组(让我们天真地将它们称为图像),并在给定x和y坐标的情况下将它们用作散布标记,而不必保存为PNG然后读取.

例如,假设你有一些相当枯燥的‘图像’:

import numpy as np
images = np.random.uniform(0,1,(5,10,10))

...也就是说,我们有5幅10x10的2D图像.

如果我们想要在由x和y坐标指定的以下5个位置绘制这些‘图像’作为标记:

x, y, = np.array([0, 2, -3, 6, 6.5]), np.array([10, 3, -2, -1, 0.2])

...做这件事最好的方法是什么?


我try 过的最接近的例子,但未能奏效:

import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
from matplotlib.offsetbox import AnnotationBbox, OffsetImage

# Convert the images into PIL images
# How? Using: https://stackoverflow.com/a/62144323/8188120
# Why? Maybe PIL images are nice and easy for plotting as markers.. I'm grasping at straws really

pil_images = []
for i in range(images.shape[0]):
    pil_images.append(Image.fromarray(np.uint8(images[i])).convert('RGB'))

# Try plotting the images as markers
# Why this method? Saw it in this thread and continued grasping for more straws: https://stackoverflow.com/a/53851017/8188120

fig, ax = plt.subplots()
for i in range(len(pil_images)):
    ab = AnnotationBbox(OffsetImage(pil_images[i]), x[i], y[i], frameon=False)
    ax.add_artist(ab)
fig.savefig(image_path + 'funny_markers.png')
plt.close('all')

推荐答案

您需要相应地设置轴的限制,否则它们将默认为仅(0,1):

from matplotlib.offsetbox import OffsetImage, AnnotationBbox
fig, ax = plt.subplots()
for x0, y0, img in zip(x, y, images):
    ab = AnnotationBbox(OffsetImage(img, zoom=5, cmap='gray'), (x0, y0), frameon=False)
    ax.add_artist(ab)
plt.xlim(x.min(), x.max()+1)
plt.ylim(y.min(), y.max()+1)
plt.show()

输出:

enter image description here

Python相关问答推荐

pandas MultiIndex是SQL复合索引的对应物吗?

这些变量是否相等,因为它们引用相同的实例,尽管它们看起来应该具有不同的值?

Python(Polars):使用之前的变量确定当前解决方案的Vector化操作

使用itertools出现第n个子串

如何使用关键参数按列对Pandas rame进行排序

如何将不同长度的新列添加到现有的框架中

如何从格式为note:{neighbor:weight}的字典中构建networkx图?

如何在Python中增量更新DF

如何在vercel中指定Python运行时版本?

Matplotlib轮廓线值似乎不对劲

如何将桌子刮成带有Se的筷子/要求/Beautiful Soup ?

时间序列分解

仿制药的类型铸造

Django mysql图标不适用于小 case

使可滚动框架在tkinter环境中看起来自然

如何使用LangChain和AzureOpenAI在Python中解决AttribeHelp和BadPressMessage错误?

如何更改分组条形图中条形图的 colored颜色 ?

创建可序列化数据模型的最佳方法

如何在两列上groupBy,并使用pyspark计算每个分组列的平均总价值

Python—压缩叶 map html作为邮箱附件并通过sendgrid发送