将图像注释添加到条形图中

2024-03-16

举例来说,假设我有一些数据

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

我确实想把它们画成这样

this.

如何将这些标志图片放入图表中(如果可能的话)? 其次,我怎样才能自动化这个过程?


该解决方案适用于使用以下命令生成的轴级别图matplotlib, seaborn, and pandas.DataFrame.plot.

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

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

     def get_flag(name):
         path = "path/to/flag/{}.png".format(name)
         im = plt.imread(path)
         return im
    
  2. 将图像放置在绘图中的特定位置。这可以通过使用OffsetImage https://matplotlib.org/api/offsetbox_api.html#matplotlib.offsetbox.OffsetImage。可以在以下位置找到一个示例matplotlib 页面 http://matplotlib.org/examples/pylab_examples/demo_annotation_box.html。最好使用一个函数,该函数以国家名称和位置作为参数并生成一个AnnotationBboxOffsetImage inside.

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

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

最终结果可能如下所示:

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()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将图像注释添加到条形图中 的相关文章

随机推荐