如何按灾害类型绘制各灾害年度发生数量的多时间序列折线图
问题原因
reset_index()默认返回新DataFrame,你未将结果赋值给yearly_tcount,所以该对象仍保留Start_year、Disaster_Type为复合索引,没有转为普通列,访问yearly_tcount['Start_year']自然触发KeyError。- 灾害类型筛选语法错误,且列名大小写不匹配:实际列名为
Disaster_Type(T大写),你写的Disaster_type为小写t,同时布尔索引的书写格式不符合pandas规范。
单条折线(洪水)修复代码
替换你原来的问题代码段为以下内容即可正常绘制洪水灾害的年度变化折线:
# 统计每年各类型灾害发生次数 df_yearly_tcount = df_time.groupby(['Start_year', 'Disaster_Type']).size() yearly_tcount = pd.DataFrame(df_yearly_tcount) # 重置索引并给计数字段命名 yearly_tcount = yearly_tcount.reset_index().rename(columns={0: 'Disaster_Count'}) # 筛选洪水灾害数据 flood_df = yearly_tcount[yearly_tcount['Disaster_Type'] == 'Flood'] X = flood_df['Start_year'] y = flood_df['Disaster_Count'] plt.plot(X, y, label='Flood') plt.legend() plt.show()
所有灾害多折线图实现
如果需要一次性绘制所有灾害类型的折线对比,直接调用seaborn的lineplot即可自动按灾害类型分色绘制:
plt.figure(figsize=(14, 7)) # 按灾害类型分组绘制折线 sns.lineplot( data=yearly_tcount, x='Start_year', y='Disaster_Count', hue='Disaster_Type', marker='o', linewidth=2 ) plt.title('各类型灾害年度发生次数变化趋势', fontsize=14) plt.xlabel('年份', fontsize=12) plt.ylabel('发生次数', fontsize=12) plt.legend(title='灾害类型', bbox_to_anchor=(1.05, 1), loc='upper left') plt.grid(alpha=0.3) plt.tight_layout() plt.show()
内容的提问来源于stack exchange,提问作者JamesArthur
相关产品推荐
相关产品推荐

