Matplotlib绘制柱状图时X轴仅显示间隔年份标签的问题
问题:Matplotlib柱状图X轴年份仅显示间隔值,需显示全部年份
我从文件读取DataFrame绘制柱状图,数据能正常展示,但X轴只显示间隔2的年份(比如2000、2002、2004),希望显示所有年份标签。
原代码
import seaborn as sn import matplotlib.pyplot as plt import pandas as pd # 读取数据 topics_df = pd.read_csv("../myData/topicsData.csv") print(topics_df) print("\n") print(topics_df.Sexeducation) print(topics_df.Year) plt.bar(topics_df.Year, topics_df.Sexeducation, color="blue", width=0.4) plt.show()
DataFrame数据示例
Year Sexeducation Plants DigestiveSystem BreathingSystem Diseases 0 2000 2 3 4 5 7 1 2001 5 7 1 3 1 2 2002 3 1 4 1 3 3 2003 9 8 1 5 6 4 2004 3 2 7 6 1 5 2005 1 4 2 1 0 6 2006 5 5 1 3 3 7 2007 1 2 4 1 5 8 2008 1 3 4 5 4
当前效果图

解决方法
Matplotlib默认会自动优化X轴刻度,导致部分年份被隐藏。可以通过两种简单方式强制显示所有年份:
方法1:手动指定X轴刻度
在调用plt.show()前添加一行代码,直接把所有年份设为X轴刻度:
plt.xticks(topics_df.Year)
修改后的完整代码:
import seaborn as sn import matplotlib.pyplot as plt import pandas as pd # 读取数据 topics_df = pd.read_csv("../myData/topicsData.csv") print(topics_df) print("\n") print(topics_df.Sexeducation) print(topics_df.Year) plt.bar(topics_df.Year, topics_df.Sexeducation, color="blue", width=0.4) # 设置X轴显示所有年份 plt.xticks(topics_df.Year) plt.show()
方法2:将年份转为字符串类型
把Year列转为字符串后,Matplotlib会将其视为分类标签,默认显示所有值:
topics_df['Year'] = topics_df['Year'].astype(str)
修改后的核心代码片段:
# 读取数据 topics_df = pd.read_csv("../myData/topicsData.csv") # 将年份转为字符串类型 topics_df['Year'] = topics_df['Year'].astype(str) print(topics_df) print("\n") print(topics_df.Sexeducation) print(topics_df.Year) plt.bar(topics_df.Year, topics_df.Sexeducation, color="blue", width=0.4) plt.show()
补充:避免标签重叠
如果年份较多导致标签挤在一起,可以添加旋转参数调整显示角度:
plt.xticks(topics_df.Year, rotation=45)
内容的提问来源于stack exchange,提问作者alson
相关产品推荐
相关产品推荐

