如何按日期范围与航空公司分组并绘制带标注柱状图
解决方案:航空公司乘客数据分组与可视化
一、数据预处理:筛选目标航空公司并按自定义周期分组
首先筛选出Air Canada和American Pan Pacific两家公司的数据,再按自定义日期周期(半年/年度)与航空公司分组,计算周期内总乘客数:
import pandas as pd import numpy as np import matplotlib.pyplot as plt # 筛选目标航空公司 target_airlines = ['Air Canada', 'American Pan Pacific'] filtered_df = test[test['Operating_Airlines'].isin(target_airlines)].copy() # 按半年周期分组('6M'=半年,'Y'=年度,可替换为其他频率如'Q'=季度) grouped_df = filtered_df.groupby([ pd.Grouper(key='Dates', freq='6M'), 'Operating_Airlines' ])['Passenger_Count'].sum().unstack(fill_value=0) # 自定义日期显示格式为Y-m-d grouped_df.index = grouped_df.index.strftime('%Y-%m-%d')
二、绘制带数值标注的双柱图
采用双柱布局避免重叠,同时为每个柱子添加数值标注:
# 设置画布大小 fig, ax = plt.subplots(figsize=(12, 6)) bar_width = 0.35 x = range(len(grouped_df.index)) # 绘制两家航空公司的柱子 rects1 = ax.bar([i - bar_width/2 for i in x], grouped_df['Air Canada'], width=bar_width, label='Air Canada') rects2 = ax.bar([i + bar_width/2 for i in x], grouped_df['American Pan Pacific'], width=bar_width, label='American Pan Pacific') # 定义标注函数:在柱子上方显示千分位格式化的数值 def add_value_labels(rects): for rect in rects: height = rect.get_height() ax.annotate(f'{height:,}', xy=(rect.get_x() + rect.get_width()/2, height), xytext=(0, 3), textcoords='offset points', ha='center', va='bottom') add_value_labels(rects1) add_value_labels(rects2) # 配置图表样式 ax.set_xlabel('统计周期') ax.set_ylabel('总乘客数') ax.set_title('Air Canada与American Pan Pacific分周期总乘客数') ax.set_xticks(x) ax.set_xticklabels(grouped_df.index, rotation=45, ha='right') ax.legend() plt.tight_layout() plt.show()
三、年度周期下自定义日期范围
如果需要非自然年的年度周期(比如财年:每年7月至次年6月),可以通过freq='AS-JUL'指定年度起始月份:
# 按7月起始的财年分组 grouped_fiscal_year = filtered_df.groupby([ pd.Grouper(key='Dates', freq='AS-JUL'), # AS-JUL表示年度从7月1日开始 'Operating_Airlines' ])['Passenger_Count'].sum().unstack(fill_value=0) # 自定义财年标签显示格式 grouped_fiscal_year.index = [f'{y}/{y+1}财年' for y in grouped_fiscal_year.index.year]
后续绘图逻辑与双柱图代码一致,仅需将grouped_df替换为grouped_fiscal_year即可。
原代码问题分析
你之前的代码未成功的核心原因:
- 列名不匹配:原DataFrame日期列为
Dates而非Date,航空公司列为Operating_Airlines而非Operating_Airline - 未做分组聚合:直接调用
count()会返回整列计数,没有按日期+航空公司维度分组 - 双柱布局错误:未调整柱子宽度与位置,导致两个系列的柱子完全重叠
内容的提问来源于stack exchange,提问作者Qas
相关产品推荐
相关产品推荐

