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,容易被截断。
你可以用以下两种方法修复:
- 读取时指定索引列(如果你的csv文件里有专门的月份列,比如列名叫
Month):
flight_delays = pd.read_csv(r'C:\Users\Matt\Desktop\Portfolio Projects\seaborn_work\flight_delays.csv', index_col='Month')
- 手动设置索引(如果csv里没有单独月份列,只有12行数据):
在读取csv后添加一行代码:
flight_delays.index = range(1, 13)
修改后再运行代码,X轴就能正常显示1-12月了。
内容的提问来源于stack exchange,提问作者snakemint
相关产品推荐
相关产品推荐

