【问题标题】:How to change date format on x-axis [duplicate]如何更改x轴上的日期格式[重复]
【发布时间】:2021-11-28 04:57:39
【问题描述】:

目前我有这个代码:

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=[date(2021,i,1) for i in z]
        y=[i[1] for i in z]
        plt.plot(x, y)
        plt.show()
        main()
    else:
        print('Sorry! There is not enough information to create a graph of you spending over time.')
        main()

但图表不是我想要的。我想将 x 轴更改为更好的版本,例如2021-10,我想省略这一天

enter image description here

【问题讨论】:

标签: python matplotlib spyder


【解决方案1】:

您必须为 x 轴定义 DateFormatter。在您的情况下,您只需要几年和几个月。这是符号:'%Y-%m' 和下面你可以看到如何应用格式化程序。

myFmt = mdates.DateFormatter('%Y-%m')
ax1.xaxis.set_major_formatter(myFmt)

示例 本文改编自here

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.cbook as cbook
# Fixing random state for reproducibility
np.random.seed(19680801)

# load up some sample financial data
r = (cbook.get_sample_data('goog.npz', np_load=True)['price_data']
     .view(np.recarray))
# create two subplots with the shared x and y axes

fig = plt.figure()
ax1 = fig.add_subplot(1, 1, 1)
ax1.plot(r.date, r.close, lw=2)
myFmt = mdates.DateFormatter('%Y-%m')
plt.xticks(rotation=45)
ax1.xaxis.set_major_formatter(myFmt)

【讨论】:

    猜你喜欢
    • 2014-10-03
    • 2013-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多