Display label stacked barh with values from dataframe

前端 未结 1 1753
遇见更好的自我
遇见更好的自我 2020-12-20 04:14

How can I display values for my stacked barh chart that come from a dataframe? How can I place the labels above their respective sections on each bar and modify the font so

相关标签:
1条回答
  • 2020-12-20 05:07

    You can do this similarly as in the referenced question, by annotating the bars. For a stacked bar chart you'll have to tweak the position of the labels a little to get them where you want. You can play around with the horizontalalignment, verticalalignment and adding a bit of a margin as I did (+.5).

    import numpy as np
    import pandas as pd
    import matplotlib.pyplot as plt
    from cycler import cycler
    
    #used gray colormap, you can use your own colors by replacing colormap='gray' with color=colors
    colors = ["#252525", "#636363", "#969696", "#cccccc", "#f7f7f7"]
    plt.rcParams['axes.prop_cycle'] = cycler(color=colors)
    
    #dummy data
    df = pd.DataFrame(np.random.randint(5, 8, (10, 3)), columns=['Group1', 'Group2', 'Group3'])
    
    for col in df.columns.tolist():
        df[col] = df[col].apply(lambda x:x*100 / df[col].sum())
    
    ax = df.T.plot.barh(stacked=True, colormap='gray', edgecolor='black', linewidth=1)
    
    for lbl in ax.patches:
        ax.annotate("{:.0f}%".format(int(lbl.get_width())), (lbl.get_x(), lbl.get_y()+.5), verticalalignment='bottom', horizontalalignment='top', fontsize=8, color='black')
    
    ax.legend(loc='center left', bbox_to_anchor=(1.0, .5))
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.spines['bottom'].set_visible(False)
    ax.spines['left'].set_visible(False)
    
    plt.show()
    

    0 讨论(0)
提交回复
热议问题