【问题标题】:How to display y-bar values in the bar chart?如何在条形图中显示 y-bar 值?
【发布时间】:2020-09-18 00:39:56
【问题描述】:

朋友们好,我正在使用seabornmatplotlib 创建条形图。我制作了一个成功的图表,但我不知道如何在图表上显示 y 条形值。请给我建议和不同的技术来在图上显示 y-bar 值。

请帮我解决问题。

谢谢

plt.figure(figsize = (10,5))
sns.countplot(x='subject',data=udemy,hue='is_paid')

【问题讨论】:

标签: python matplotlib seaborn data-science


【解决方案1】:

不幸的是,seaborn 中的 countplot 不允许同时传递 x 和 y 值,每个绘图只能传递一个。

您尝试过不同的图表吗? 例如plt.bar() 并将 xticks 和 yticks 设置为您想要的值?

【讨论】:

    【解决方案2】:

    简答:您需要自定义自动标签机制。

    首先让我们说清楚。如果你的意思是

    我不知道如何在绘图上显示 y 条形值

    • 在酒吧(内部),那么这个answer 会很有帮助。

    • 在条的顶部(外部),除了seaborn 的这个答案之外,还有一些自动标签解决方案here 你可以使用它以及this example。最近如果你安装了新的matpotlib v.3.4.0你可以使用bar_label()Ref.

    我还可以为您提供受matplotlib documenetation 启发的方法,使用手动调整以最适合在条形图中使用matplotlib 以函数形式在条形图中打印值/文本:

    from matplotlib import pyplot as plt
    import numpy as np
    
    
    def bar_plot(ax, data, colors=None, total_width=0.8, single_width=1, legend=True):
        
    
        # Check if colors where provided, otherwhise use the default color cycle
        if colors is None:
            colors = plt.rcParams['axes.prop_cycle'].by_key()['color']
    
        # Number of bars per group
        n_bars = len(data)
    
        # The width of a single bar
        bar_width = total_width / n_bars
    
        # List containing handles for the drawn bars, used for the legend
        bars = []
    
        # Iterate over all data
        for i, (name, values) in enumerate(data.items()):
            # The offset in x direction of that bar
            x_offset = (i - n_bars / 2) * bar_width + bar_width / 2
    
            # Draw a bar for every value of that type
            for x, y in enumerate(values):
                bar = ax.bar(x + x_offset, y, width=bar_width * single_width, color=colors[i % len(colors)])
    
            # Add a handle to the last drawn bar, which we'll need for the legend
            bars.append(bar[0])
    
        # Draw legend if we need
        if legend:
            ax.legend(bars, data.keys())
    
    
    if __name__ == "__main__":
        # Usage example:
        data = {
            "False": [100.16,  30.04, 50.04, 120.19],
            "True": [1100.08,  600.06, 650.06, 1050.17],
            #"RMSE":[0.39,  0.19, 0.20, 0.44,  0.45,  0.26],
                }
    
        fig, ax = plt.subplots(figsize=(8, 6))
        
        y_pos = np.arange(len(objects))
        for i, v in enumerate(data['False']):
            plt.text(y_pos[i] - 0.35, v + 10.213, str(v))
    
        for i, v in enumerate(data['True']):
            plt.text(y_pos[i] + 0.05, v + 10.213, str(v))
    
    
        #plt.rc('font', **font)
        bar_plot(ax, data, total_width=.8, single_width=.9)
        #font = font_manager.FontProperties(family='Comic Sans MS', weight='bold', style='normal', size=16)
        font = {'family' : 'normal',
                'weight' : 'bold',
                'size'   : 15,
                 'family':'Times New Roman'}
        #font = {'family':'Times New Roman', 'weight' :'normal','size':15}
        
        ax.set_xticklabels( ('0',' ','Business Finance',' ','Graphic Design',' ', 'Musical Instruments',' ', 'Web Development') , rotation=45, ha="right")#, **font )
        #ax.set_yticklabels( data['MSE'] ,**font )
        ax.set_ylabel('Count  ')#, **font)
        ax.set_xlabel('Subject  ')#, **font)
        ax.set_title('Figure 10/ Table 6 for is_paid')#, **font)
        #ax.legend().set_visible(False)
        plt.ylim((0.0, 1500.0))
        plt.show()
    

    输出:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-13
      相关资源
      最近更新 更多