How to write values over matplotlib bar charts without distorted figures

前端 未结 1 1165
天命终不由人
天命终不由人 2021-01-28 04:55

NOTE

The answers here produce a distorted figure; here is the bad result:

Here is the modified code that produces the bad resu

1条回答
  •  南笙
    南笙 (楼主)
    2021-01-28 05:37

    You should not hard-coded the text. Instead, try to extract the values from patches:

    def plot_compare_bar(col1, col2, frame, fig_prefix=''):
        frame = frame.sort_values(by=col1)
        ind = np.arange(len(frame))
        width = 0.4
        fig, ax = plt.subplots(figsize=(10,10))
        ax.barh(ind, frame[col1], width, color='red', label=col1)
        ax.barh(ind + width, frame[col2], width, color='blue', label=col2)
        ax.set(
            yticks=ind + width, yticklabels=frame['Class Name'],
            ylim=[2 * width - 1, len(frame)], title=(
                f'{fig_prefix} {col1} vs {col2} evaluation results'))
    
        # annotation here
        for patch in ax.patches:
            # extract information from patch
            pw = patch.get_width()
            _,y = patch.get_xy()
            color = patch.get_facecolor()
    
            ax.text(pw + 3, y + width/2, str(pw), 
                    color=color,verticalalignment='center')
    
        ax.legend(loc='lower right')
    

    Output:

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