我想将如下所示的标志图像添加到我的条形图中:
我尝试过 AnnotationBbox,但显示为方形轮廓。谁能告诉我如何完全按照上图实现此目的?
编辑:
下面是我的代码
ax.barh(y = y, width = values, color = r, height = 0.8)
height = 0.8
for i, (value, url) in enumerate(zip(values, image_urls)):
response = requests.get(url)
img = Image.open(BytesIO(response.content))
width, height = img.size
left = 10
top = 10
right = width-10
bottom = height-10
im1 = img.crop((left, top, right, bottom))
print(im1.size)
im1
ax.imshow(im1, extent = [value - 6, value, i - height / 2, i + height / 2], aspect = 'auto', zorder = 2)
编辑2:
height = 0.8
for j, (value, url) in enumerate(zip(ww, image_urls)):
response = requests.get(url)
img = Image.open(BytesIO(response.content))
ax.imshow(img, extent = [value - 6, value - 2, j - height / 2, j + height / 2], aspect = 'auto', zorder = 2)
ax.set_xlim(0, max(ww)*1.05)
ax.set_ylim(-0.5, len(yy) - 0.5)
plt.tight_layout()
可以使用 Matplotlib 的
imshow
函数将图像添加到条形图中。诀窍是使用
extent
关键字参数来精确定位和缩放图像。
以下是如何操作:
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import requests
from io import BytesIO
# 示例数据
y = ['A', 'B', 'C']
values = [10, 20, 30]
image_urls = [
"https://i.sstatic.net/1aziz.png",
"https://i.sstatic.net/1aziz.png",
"https://i.sstatic.net/1aziz.png"
]
# 创建条形图
fig, ax = plt.subplots()
bars = ax.barh(y, values, color='lightgray', height=0.8)
# 添加图像到每个条形
for i, (bar, url) in enumerate(zip(bars, image_urls)):
# 获取图像
response = requests.get(url)
img = mpimg.imread(BytesIO(response.content))
# 获取条形位置和高度
bar_width = bar.get_width()
bar_height = bar.get_height()
bar_x = bar.get_x()
bar_y = bar.get_y()
# 计算图像的范围以使其适合条形内
aspect_ratio = img.shape[1] / img.shape[0]
img_width = bar_height * aspect_ratio * 0.8 # 调整 0.8 以控制图像宽度
img_height = bar_height * 0.8
img_x = bar_x + bar_width - img_width - 0.02 # 调整 0.02 以控制图像和条形之间的间距
img_y = bar_y + (bar_height - img_height) / 2
# 添加图像到轴
ax.imshow(img, extent=[img_x, img_x + img_width, img_y, img_y + img_height], aspect='auto', zorder=2)
# 设置轴限制和其他格式
ax.set_xlim(0, max(values) * 1.1)
ax.set_ylim(-0.5, len(y) - 0.5)
plt.tight_layout()
plt.show()
这将创建具有指定图像的条形图,图像位于条形内并根据条形的高度进行缩放。代码还包括通过调整值
0.8
和
0.02
来控制图像大小和位置的注释。