自动化条形图,将国家标志显示为勾选标签

时间:2017-05-29 16:08:58

标签: python python-2.7 python-3.x matplotlib

所以,例如,让我们说我有一些数据

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

我想把它们描绘成

this

如何将这些标志图片放入图表中(如果它甚至可能)? 其次,我该如何自动化呢?

1 个答案:

答案 0 :(得分:2)

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

  1. 将标志作为数组添加到脚本中。 E.g。

    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绘制条形图。要将国家/地区名称设置为ticklabels,请使用ax.set_ticklabels(countries)。然后,对于每个国家/地区,使用循环从上方放置OffsetImage

  4. 最终结果可能如下所示:

    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()
    
相关问题