如何用Pandas将groupby分组后的统计数据绘制成直方图
基于Pandas分组后的国家营收数据绘制直方图
你已经完成了营收计算和分组统计,接下来可以按以下步骤绘制可视化图形(注:这里更适合用条形图——直方图一般用于展示连续数据的分布;如果一定要用直方图,是把营收数值分成区间统计数量,但从你的需求看,条形图更匹配展示各国的营收对比):
步骤1:保存分组结果
先把分组排序后的结果存为变量,方便后续操作:
df['Total Revenue'] = df['Quantity'] * df['UnitPrice'] # 存储分组求和并排序后的结果 country_revenue = df.groupby('Country')['Total Revenue'].sum().sort_values(ascending=False)
步骤2:用Matplotlib绘制基础条形图
Matplotlib是最常用的绘图库,代码直接易懂:
import matplotlib.pyplot as plt # 设置画布尺寸,避免国家名称重叠 plt.figure(figsize=(12, 6)) # 绘制条形图 country_revenue.plot(kind='bar') # 添加图表元素 plt.title('各国总营收对比') plt.xlabel('国家') plt.ylabel('总营收') # 旋转x轴标签,提升可读性 plt.xticks(rotation=45) # 显示图形 plt.show()
步骤3:用Seaborn绘制更美观的图形
如果想要更精致的样式,可以用Seaborn(需要先把Series转为DataFrame):
import seaborn as sns import matplotlib.pyplot as plt # 将Series转换为DataFrame,适配Seaborn的输入格式 revenue_df = country_revenue.reset_index(name='Total Revenue') plt.figure(figsize=(12, 6)) sns.barplot(data=revenue_df, x='Country', y='Total Revenue', palette='viridis') plt.title('各国总营收对比') plt.xlabel('国家') plt.ylabel('总营收') plt.xticks(rotation=45) plt.show()
步骤4:优化极端值问题
从你的数据可以看到,英国的营收远高于其他国家,会导致其他国家的条形被压缩得几乎看不清。可以通过两种方式优化:
方式一:使用对数坐标轴
plt.figure(figsize=(12, 6)) country_revenue.plot(kind='bar') plt.title('各国总营收对比(对数坐标轴)') plt.xlabel('国家') plt.ylabel('总营收(对数刻度)') plt.xticks(rotation=45) # 设置y轴为对数刻度 plt.yscale('log') plt.show()
方式二:排除极端值,聚焦其他国家
# 移除英国的数据,展示剩余国家 filtered_revenue = country_revenue.drop('United Kingdom') plt.figure(figsize=(12, 6)) filtered_revenue.plot(kind='bar') plt.title('除英国外各国总营收对比') plt.xlabel('国家') plt.ylabel('总营收') plt.xticks(rotation=45) plt.show()
内容的提问来源于stack exchange,提问作者mxid
相关产品推荐
相关产品推荐

