【问题标题】:Add image annotations to bar plots向条形图添加图像注释
【发布时间】:2017-10-30 00:12:03
【问题描述】:

例如,假设我有一些数据

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

我确实想像这样绘制它们

.

如何将这些标志图片放在图表中(如果可能的话)? 其次,我该如何自动化呢?

【问题讨论】:

    标签: python pandas matplotlib seaborn


    【解决方案1】:

    此解决方案适用于使用 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 上找到一个示例。最好使用一个函数,它以国家名称和位置作为参数,并生成一个AnnotationBbox,里面有OffsetImage

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

    (coord, 0)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()
    
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-26
    • 2021-04-09
    • 2021-10-28
    • 2019-12-23
    • 2022-08-03
    • 2016-07-03
    相关资源
    最近更新 更多