用图像注释熊猫条形图

时间:2019-08-16 21:04:55

标签: python pandas image matplotlib png

我想注释我用Pandas创建的带有'⭑'字符的水平条形图。每个酒吧的星级数由评级系统确定,该评级系统的范围从零到五颗星,并且包含半星评级。我的问题是没有1/2星号文字字符,因此我必须使用包含半星号的图像来正确注释条。

以下是从我正在使用的DataFrame创建示例的代码:

df = pd.DataFrame(index=range(7), 
                  data={'Scores': [79.0, 79.5, 81.8, 76.1, 72.8, 87.6, 79.3]})
df['Stars'] = df['Scores'].apply(real_stars)

以下是确定星级的功能:

def real_stars(x):
    if x >=88:
        return ('★★★★★')
    elif x >=83:
        return ('★★★★¹/₂')
    elif x >=79:
        return ('★★★★')
    elif x >=75:
        return ('★★★¹/₂')
    elif x >=71:
        return ('★★★')
    elif x >=67:
        return ('★★¹/₂')
    elif x >=63:
        return ('★★')
    elif x >=59:
        return ('★¹/₂')
    elif x >=55:
        return ('★')
    elif x >=50:
        return ('¹/₂★')
    else:
        return None

这是我用来绘制条形图并用星号注释每个条形右侧的代码:

fig = plt.figure(figsize=(7.5,5))
ax = plt.subplot()
plt.box(on=None) 

df.plot.barh(ax=ax, width=.75, legend=False)

for i, p in zip(df['Stars'], ax.patches):
    width, height = p.get_width(), p.get_height()
    x, y = p.get_xy() 
    ax.annotate(i, (p.get_x()+1*width, p.get_y()+.45*height), fontsize=25, 
                fontweight='bold', color='white', ha='right', va='center')

我想以完全相同的方式注释条形,但是我不想将半星评级表示为“ 1/2”,而是要包括一个半星的图像。我认为第一步是将图像合并到real_stars函数中,在df ['Stars']列中显示图像,然后使用该列进行注释。

我要使用的图像示例:

.5 star 1 star

2 个答案:

答案 0 :(得分:0)

半星字符已添加到unicode版本11中,例如:

import matplotlib.pyplot as plt
import matplotlib.font_manager as mfm

font_path = '<PATH>/Symbola.ttf'
prop = mfm.FontProperties(fname=font_path) # find this font

# Some examples of stars
uni_char = u"\u2605\U0001F7CA\u2BE8\u2BEA"
plt.annotate(uni_char, (0.5, 0.5), fontproperties=prop, fontsize=20)
plt.show()

enter image description here

请参阅this,并请注意,您必须使用支持此list中较新标准的字体。上面的示例使用Symbola

答案 1 :(得分:0)

要注释具有形状的条,可以使用vps719806.ovh.net does not allow connection,其中包含AnchoredOffsetboxDrawingArea内部的形状是在相对于偏移框的显示空间中定义的。

DrawingArea

enter image description here