【问题标题】:Grouping Bar Plot in seabornseaborn中的分组条形图
【发布时间】:2021-02-06 00:07:54
【问题描述】:

我正在尝试并排绘制两个连续变量的 BAR PLOT。没有成功。

df_cooking= df.groupby(df['region'])['cook_time','prep_time'].mean().reset_index()
df_cooking.head(6)

    region      cook_time   prep_time
0   Central     48.333333   13.333333
1   East        41.607143   43.518519
2   North       41.979167   38.020833
3   North East  28.461538   28.846154
4   South       36.909091   58.181818
5   West        41.880597   16.924242

这就是我使用 seaborn 尝试过的方式:

plt.figure(figsize=(8,9))
plt.bar(df_cooking['region'],df_cooking['prep_time'], label = 'Preparation Time', color= 'c')
plt.bar(df_cooking['region'],df_cooking['cook_time'], label = 'Cooking Time', color = 'r')

plt.xlabel('Region')
plt.ylabel('Time in Minutes')
plt.title('Cooking and Preparation Time per Region')
plt.legend()
plt.show()

提前感谢您的帮助!

【问题讨论】:

    标签: python-3.x pandas seaborn data-science


    【解决方案1】:

    要使用 seaborn,您需要将拥有的数据框转为长格式:

    df = pd.DataFrame({'region':np.random.choice(['Central','East','West'],100),
                       'cook_time':np.random.uniform(0,1,100),
                       'prep_time':np.random.uniform(0,1,100)})
    
    df_cooking= df[['cook_time','prep_time']].groupby(df['region']).mean().reset_index()
    
    df_cooking.melt(id_vars='region')
    
    region  variable    value
    0   Central cook_time   0.516703
    1   East    cook_time   0.519351
    2   West    cook_time   0.486752
    3   Central prep_time   0.463249
    4   East    prep_time   0.539191
    5   West    prep_time   0.520700
    
    sns.barplot(data=df_cooking.melt(id_vars='region'),x='region',y='value',hue='variable')
    

    【讨论】:

    • 谢谢,这正是我想要的。干杯!
    【解决方案2】:

    您的代码中没有 seaborn。也就是说,例如,您可以使用:

    df_cooking.plot.bar(x='region', y=['cook_time','prep_time'])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-04
      • 2016-12-01
      • 1970-01-01
      • 2019-09-05
      • 1970-01-01
      • 2015-12-08
      • 2021-03-01
      相关资源
      最近更新 更多