【问题标题】:How to plot graph and correct date ticks?如何绘制图表和正确的日期刻度?
【发布时间】:2021-06-19 02:08:28
【问题描述】:

我正在尝试绘制一个包含日期的图表(我希望年份和月份为 x-ticks)。但是,当我尝试绘制图表时,我要么得到正确的刻度,但没有显示图表(这是我最后有 ax.plot()... 的时候),或者图表显示但得到错误(无法转换值( s) 到轴单位:numpy.datetime64('2020'))。我不知道如何解决这个问题。 这是我的一段代码:

years = mdates.YearLocator()
months = mdates.MonthLocator()
years_fmt = mdates.DateFormatter('%Y')



fig, ax = plt.subplots(1,1, figsize = (10,10))
ax.plot(Date_of_report, Total_reported)
#format ticks
ax.xaxis.set_major_locator(years)
ax.xaxis.set_major_formatter(years_fmt)
ax.xaxis.set_minor_locator(months)

#round nearest years
datemin = np.datetime64(Date_of_report[0], 'Y')
datemax = np.datetime64(Date_of_report[-1], 'Y') + np.timedelta64(1, 'Y')
ax.set_xlim(datemin, datemax)


ax.format_xdata = mdates.DateFormatter('%Y-%d-%m')
ax.grid(True)
fig.autofmt_xdate()
fig.show()

【问题讨论】:

  • 很难知道我们是否不知道您的约会形式是什么。也许您可以包含一些模拟数据。

标签: date matplotlib graph xticks


【解决方案1】:

我找到了解决方案。导入数据时,我将日期作为字符串导入。相反,我将其导入为 dtype='datetime64[ns]'

np.loadtxt('/content/gdrive/MyDrive/corono/COVID-19_uitgevoerde_testen.csv',\
                       delimiter =';',skiprows=1, usecols=2, dtype='datetime64[ns]')

【讨论】:

    猜你喜欢
    • 2019-03-03
    • 1970-01-01
    • 1970-01-01
    • 2014-06-12
    • 1970-01-01
    • 2016-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多