Seaborn Barplot - Displaying Values

后端 未结 6 785
不知归路
不知归路 2020-11-27 14:39

I\'m looking to see how to do two things in Seaborn with using a bar chart to display values that are in the dataframe, but not in the graph

1) I\'m looking to displ

6条回答
  •  鱼传尺愫
    2020-11-27 14:56

    Just in case if anyone is interested in labeling horizontal barplot graph, I modified Sharon's answer as below:

    def show_values_on_bars(axs, h_v="v", space=0.4):
        def _show_on_single_plot(ax):
            if h_v == "v":
                for p in ax.patches:
                    _x = p.get_x() + p.get_width() / 2
                    _y = p.get_y() + p.get_height()
                    value = int(p.get_height())
                    ax.text(_x, _y, value, ha="center") 
            elif h_v == "h":
                for p in ax.patches:
                    _x = p.get_x() + p.get_width() + float(space)
                    _y = p.get_y() + p.get_height()
                    value = int(p.get_width())
                    ax.text(_x, _y, value, ha="left")
    
        if isinstance(axs, np.ndarray):
            for idx, ax in np.ndenumerate(axs):
                _show_on_single_plot(ax)
        else:
            _show_on_single_plot(axs)
    

    Two parameters explained:

    h_v - Whether the barplot is horizontal or vertical. "h" represents the horizontal barplot, "v" represents the vertical barplot.

    space - The space between value text and the top edge of the bar. Only works for horizontal mode.

    Example:

    show_values_on_bars(sns_t, "h", 0.3)
    

提交回复
热议问题