如何修改matplotlib绘图x轴的日期格式,省略日期中的日字段
实现方案
你可以通过matplotlib内置的日期格式化工具调整x轴显示样式,同时注意修正原有代码中x轴数据构造的逻辑错误,修改后代码如下:
from matplotlib import dates as mdates # 请将该行导入放在代码文件头部 def graph_s(self): ex_list = list() time = list() if(len(self.sheet) > 1): for index, row in self.sheet.iterrows(): ts = date(int(row['Year']), int(row['Month']), 1) time.append(ts) ex_list.append(float(row['grocery']) + float(row['transportation']) + float(row['leisure']) + float(row['utilities']) + float(row['savings']) + float(row['bills'])) z = sorted(zip(time,ex_list)) # 修正原有x轴构造的逻辑错误 x=[i[0] for i in z] y=[i[1] for i in z] plt.plot(x, y) # 新增x轴日期格式设置 ax = plt.gca() date_format = mdates.DateFormatter('%Y-%m') ax.xaxis.set_major_formatter(date_format) # 可选优化:旋转x轴标签避免重叠 plt.xticks(rotation=45) plt.tight_layout() plt.show() main() else: print('Sorry! There is not enough information to create a graph of you spending over time.') main()
- 格式化规则中
%Y对应4位年份,%m对应2位数字月份,组合后即可输出2021-10样式的日期标签,自动省略日部分 - 新增的
plt.xticks和plt.tight_layout为可选优化项,避免日期标签过长互相挤压、被画布截断
内容的提问来源于stack exchange,提问作者user21
相关产品推荐
相关产品推荐

