Python数据分析:如何合并两个.groupby()生成的.barh()条形图?
问题:合并两个分组后的水平条形图
作为Python数据分析认证期末项目的新手,我需要合并两个通过groupby()和plot.barh()生成的水平条形图:
求和的绘图代码:
day_df.groupby(by = ["yr", "season", "weathersit"]).agg({"cnt" : "sum"}).plot.barh()
求均值的绘图代码:
day_df.groupby(by = ["yr", "season", "weathersit"]).agg({"cnt" : "mean"}).plot.barh()
我尝试了以下代码但无法运行:
#Defining Variables day_mean_dataframe = pd.DataFrame(day_df.groupby(by = ["yr", "season", "weathersit"]).agg({"cnt" : "mean"})) day_sum_dataframe = pd.DataFrame(day_df.groupby(by = ["yr", "season", "weathersit"]).agg({"cnt" : "sum"})) r1 = np.arange(6) width1 = 0.5 # Creating the subplot plt.subplot(1, 2, 2) plt.bar(r1, day_mean_dataframe["yr", "season", "weathersit"], width = width1) plt.bar(r1 + width1, day_sum_dataframe["yr", "season", "weathersit"], width = width1) # Displaying the plot plt.show()
解决方案
步骤1:合并数据到同一个DataFrame
先一次性计算cnt的总和与均值,避免重复分组操作,同时把分组索引转为普通列:
import pandas as pd import matplotlib.pyplot as plt import numpy as np # 一次性计算sum和mean,并重置索引 combined_df = day_df.groupby(["yr", "season", "weathersit"])["cnt"].agg(["sum", "mean"]).reset_index()
步骤2:生成易读的分组标签
把三个分组列合并成字符串标签,方便在图表y轴显示:
combined_df["group_label"] = combined_df.apply( lambda row: f"Year:{row['yr']} | Season:{row['season']} | Weather:{row['weathersit']}", axis=1 )
步骤3:绘制并排水平条形图
使用matplotlib绘制两组水平条形,调整位置实现并排效果:
bar_height = 0.35 # 水平条形的高度 y_pos = np.arange(len(combined_df)) # y轴位置索引 plt.figure(figsize=(12, 8)) # 绘制总和条形 plt.barh(y_pos - bar_height/2, combined_df["sum"], height=bar_height, label="Total cnt", color="#1f77b4") # 绘制均值条形 plt.barh(y_pos + bar_height/2, combined_df["mean"], height=bar_height, label="Average cnt", color="#ff7f0e") # 设置y轴标签、标题和图例 plt.yticks(y_pos, combined_df["group_label"]) plt.title("Total vs Average Bike Rentals by Year, Season and Weather", fontsize=14) plt.xlabel("Number of Rentals", fontsize=12) plt.legend(fontsize=12) # 调整布局,防止标签被截断 plt.tight_layout() plt.show()
原代码问题说明
- 索引列访问错误:
day_mean_dataframe["yr", "season", "weathersit"]是错误的,因为这三个是分组后的索引,不是DataFrame的列,需要用reset_index()转为普通列才能访问。 - 固定y轴数量:
r1 = np.arange(6)假设分组数固定为6,但实际分组数可能随数据变化,应该根据combined_df的长度动态生成。 - 子图使用错误:
plt.subplot(1,2,2)只创建了第二个子图,且你的需求是合并为并排条形,不是分开展示两个子图。
内容的提问来源于stack exchange,提问作者Connor857
相关产品推荐
相关产品推荐

