【问题标题】:Plotting multiple bar charts绘制多个条形图
【发布时间】:2020-07-22 11:03:56
【问题描述】:

我想创建一个以两个城市为重点的条形图。我的数据集与此类似。

    city      rate     Bedrooms
    Houston 132.768382      0
    Dallas  151.981043      1
    Dallas  112.897727      3
    Houston 132.332665      1
    Houston 232.611185      2
    Dallas  93.530662       4

我已将它们分解为仅包含达拉斯和休斯顿的数据框。喜欢

dal.groupby('bedrooms')['rate'].mean().plot(kind='bar')

&

hou.groupby('bedrooms')['rate'].mean().plot(kind='bar') 

我将如何制作一个条形图,根据卧室类型列出平均挂牌率。我在Python matplotlib multiple bars 找到了类似于下面这张图片的东西。标签是城市。

如果有任何帮助,我将不胜感激!

【问题讨论】:

  • 嗨史蒂夫,你可以考虑接受一个答案。

标签: python pandas matplotlib bar-chart


【解决方案1】:

您可以在这里阅读更多内容:https://pythonspot.com/matplotlib-bar-chart/


import numpy as np
import matplotlib.pyplot as plt

# data to plot
n_groups = # of data points for each
mean_rates_houston = [average rates of bedrooms for Houston]
mean_rates_dallas = [average rates of bedrooms for Dalls]

# create plot
fig, ax = plt.subplots()
index = np.arange(n_groups)
bar_width = 0.35
opacity = 0.8

rects1 = plt.bar(index, mean_rates_dallas, bar_width,
alpha=opacity,
color='b',
label='Dallas')

rects2 = plt.bar(index + bar_width, mean_rates_houston, bar_width,
alpha=opacity,
color='g',
label='Houston')

plt.xlabel('City')
plt.ylabel('Rates')
plt.title('Bedroom Rates per City')

# whatever the number of bedrooms in your dataset might be: change plt.xticks
plt.xticks(index + bar_width, ('0', '1', '2', '3')) 

plt.legend()
plt.tight_layout()
plt.show()

【讨论】:

    【解决方案2】:

    这是在 matplotlib 中执行此操作的基本方法:

    import numpy as np
    import matplotlib.pyplot as plt
    
    
    data_dallas = dal.groupby('bedrooms')['rate'].mean()
    data_houston = hou.groupby('bedrooms')['rate'].mean()
    
    fig, ax = plt.subplots()
    
    x = np.arange(5)  # if the max. number of bedrooms is 4
    width = 0.35      # width of one bar
    
    dal_bars = ax.bar(x, data_dallas, width)
    hou_bars = ax.bar(x + width, data_houston, width)
    
    ax.set_xticks(x + width / 2)
    ax.set_xticklabels(x)
    ax.legend((dal_bars[0], hou_bars[0]), ('Dallas', 'Houston'))
    
    plt.show()
    

    【讨论】:

      【解决方案3】:

      在这种情况下,Seaborn 是您的朋友,首先创建一个分组数据框,其中每个城市和卧室的平均 rate 并用 seaborn 绘制它

      import seaborn as sns
      
      dal_group = dal.groupby(['city' , 'Bedrooms']).agg({'rate': 'mean'}).reset_index()
      sns.barplot(data=dal_group, x='Bedrooms', y='rate', hue='city')
      

      使用上面的数据,它会产生这个图:

      【讨论】:

      • 不错的解决方案。这里不需要agg。
      【解决方案4】:

      有一个简单的解决方案,只使用一行pandas(只要你先重新排列数据)或使用plotly

      数据

      import pandas as pd
      df =  pd.DataFrame({'city': {0: 'Houston',
        1: 'Dallas',
        2: 'Dallas',
        3: 'Houston',
        4: 'Houston',
        5: 'Dallas'},
       'rate': {0: 132.768382,
        1: 151.981043,
        2: 112.897727,
        3: 132.332665,
        4: 232.611185,
        5: 93.530662},
       'Bedrooms': {0: 0, 1: 1, 2: 3, 3: 1, 4: 2, 5: 4}})
      
      # groupby
      df = df.groupby(["city", "Bedrooms"])["rate"].mean().reset_index()
      

      熊猫 - Matplotlib

      使用pivot_table,我们可以重新排列我们的数据

      pv = pd.pivot_table(df, 
                     index="Bedrooms",
                     columns="city",
                     values="rate")
      
      city          Dallas     Houston
      Bedrooms                        
      0                NaN  132.768382
      1         151.981043  132.332665
      2                NaN  232.611185
      3         112.897727         NaN
      4          93.530662         NaN
      
      

      然后只画一行。

      pv.plot(kind="bar");
      

      使用绘图

      import plotly.express as px
      
      px.bar(df, x="Bedrooms", y="rate", color="city",barmode='group')
      

      【讨论】:

        猜你喜欢
        • 2020-09-15
        • 2021-11-03
        • 2021-10-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-09
        • 1970-01-01
        相关资源
        最近更新 更多