python - 如何将图像添加到轴中的条形(matplotlib)

标签 python matplotlib plot figure axes

我想在条形图中添加如下标志图像:

enter image description here

我尝试过 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()

enter image description here

最佳答案

要完成@johanC 的回答,可以使用来自 iso-flags-png 的标志在 GNU/linux 和 iso3166 下 python 包:

import matplotlib.pyplot as plt
from iso3166 import countries
import matplotlib.image as mpimg


def pos_image(x, y, pays, haut):
    pays = countries.get(pays).alpha2.lower()
    fichier = "/usr/share/iso-flags-png-320x240"
    fichier += f"/{pays}.png"
    im = mpimg.imread(fichier)
    ratio = 4 / 3
    w = ratio * haut
    ax.imshow(im,
              extent=(x - w, x, y, y + haut),
              zorder=2)


plt.style.use('seaborn')
fig, ax = plt.subplots()

liste_pays = [('France', 10), ('USA', 9), ('Spain', 5), ('Italy', 5)]

X = [p[1] for p in liste_pays]
Y = [p[0] for p in liste_pays]

haut = .8
r = ax.barh(y=Y, width=X, height=haut, zorder=1)
y_bar = [rectangle.get_y() for rectangle in r]
for pays, y in zip(liste_pays, y_bar):
    pos_image(pays[1], y, pays[0], haut)


plt.show()

这使:
enter image description here

关于python - 如何将图像添加到轴中的条形(matplotlib),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61971090/

相关文章:

python - 我想根据方法的参数对方法中的列表进行排序

python matplotlib pcolor空白空间

python - 从 pie matplotlib 饼图中获取图例中的百分比

r - 在同一窗口中绘制一个或多个图

java - 如何在 Python 中使用 tensorflow 训练图像分类器模型并在 Java 应用程序中使用训练后的模型?

python - 理解 Python 引用

python - 具有张量函数的 Theano 梯度

python - 如何在 pandas 和 matplotlib 中使用 1e7 避免轴值

python - 绘制系列饼图

r - 将函数变量插入R中的图形标题