微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何绘制图形和更正日期刻度?

如何解决如何绘制图形和更正日期刻度?

我正在尝试绘制一个带有日期的图表(我想要年和月作为 x 刻度)。但是当我尝试绘制图形时,我要么得到正确的刻度但没有显示图形(这是当我有 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()

解决方法

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。