You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python绘制柱状图时X轴变量被截断的问题求助

问题:Seaborn柱状图仅显示1-11月,无法展示12月

我用PyCharm跟着Kaggle的Seaborn教程绘制航班延误柱状图,教程里X轴能显示1-12月,但我的代码运行后只到11月。尝试用xlim解决没成功,附上代码求帮助:

import pandas as pd
pd.plotting.register_matplotlib_converters()
import matplotlib.pyplot as plt
import seaborn as sns
print("Setup Complete")

flight_delays = pd.read_csv(r'C:\Users\Matt\Desktop\Portfolio Projects\seaborn_work\flight_delays.csv')
print(flight_delays)

plt.figure(figsize=(10,6))
sns.barplot(x=flight_delays.index, y=flight_delays['NK'])
plt.ylabel("Arrival delay (In minutes)")
plt.title("Average Arrival Delay for Spirit Airline Flights, by Month")
plt.show()
解决方案

问题出在数据集的索引上:

  • 教程里的flight_delays数据集索引是1-12,对应1-12月;而你直接读取csv时,pandas默认会生成0-11的索引,导致最后一个12月的柱子对应索引11,容易被截断。

你可以用以下两种方法修复:

  1. 读取时指定索引列(如果你的csv文件里有专门的月份列,比如列名叫Month):
flight_delays = pd.read_csv(r'C:\Users\Matt\Desktop\Portfolio Projects\seaborn_work\flight_delays.csv', index_col='Month')
  1. 手动设置索引(如果csv里没有单独月份列,只有12行数据):
    在读取csv后添加一行代码:
flight_delays.index = range(1, 13)

修改后再运行代码,X轴就能正常显示1-12月了。

内容的提问来源于stack exchange,提问作者snakemint

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 01:06:40