gpt4 book ai didi

python - 向条形图添加图像注释

转载 作者:太空宇宙 更新时间:2023-11-04 09:59:44 25 4
gpt4 key购买 nike

例如,假设我有一些数据

countries = ["Norway", "Spain", "Germany", "Canada", "China"]
valuesA = [20, 15, 30, 5, 26]
valuesB = [1, 5, 3, 6, 2]

我确实想把它们画成这样

this .

如何将这些旗帜图片放入图表中(如果可能的话)?其次,如何实现自动化?

最佳答案

此解决方案适用于使用 matplotlibseabornpandas.DataFrame.plot 生成的轴级图。

主要思想是将问题分成小块:

  1. 将标志作为数组获取到脚本中。例如

     def get_flag(name):
    path = "path/to/flag/{}.png".format(name)
    im = plt.imread(path)
    return im
  2. 将图像放置在图中的特定位置。这可以使用 OffsetImage 来完成.可以在 matplotlib page 上找到示例.最好使用将国家名称和位置作为参数的函数,并生成一个包含 OffsetImageAnnotationBbox

  3. 使用 ax.bar 绘制条形图。要将国家名称设置为刻度标签,请使用 ax.set_ticklabels(countries)。然后为每个国家/地区放置 OffsetImage从上面使用循环。

(coord, 0)xybox=(0., -16.) 可以调整以将图像注释放置在任何位置。

最终的结果可能是这样的:

enter image description here

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

def get_flag(name):
path = "data/flags/Flags/flags/flags/24/{}.png".format(name.title())
im = plt.imread(path)
return im

def offset_image(coord, name, ax):
img = get_flag(name)
im = OffsetImage(img, zoom=0.72)
im.image.axes = ax

ab = AnnotationBbox(im, (coord, 0), xybox=(0., -16.), frameon=False,
xycoords='data', boxcoords="offset points", pad=0)

ax.add_artist(ab)


countries = ["Norway", "Spain", "Germany", "Canada", "China"]
valuesA = [20, 15, 30, 5, 26]


fig, ax = plt.subplots()

ax.bar(range(len(countries)), valuesA, width=0.5,align="center")
ax.set_xticks(range(len(countries)))
ax.set_xticklabels(countries)
ax.tick_params(axis='x', which='major', pad=26)

for i, c in enumerate(countries):
offset_image(i, c, ax)

plt.show()

关于python - 向条形图添加图像注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44246650/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com