如何从某些日期中缺少某些值的数据绘制线图?

2024-04-25 23:50:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我不明白为什么我的情节没有告诉我我所期望的。我的情节看起来杂乱无章,我不确定是否是因为表格错过了一些日期。我应该如何用代码修复它

我的数据

date    count
0   2020-03-06  1
1   2020-03-17  2
2   2020-03-18  1
3   2020-03-21  1
4   2020-03-23  1
... ... ...
196 2020-12-27  25
197 2020-12-28  5
198 2020-12-29  19
199 2020-12-30  25
200 2020-12-31  23

我的代码

plt.plot(data['date'],data['count'])
plt.setp(plt.gca().xaxis.get_majorticklabels(),rotation=45)
plt.gca().xaxis.set_major_locator(mdates.DayLocator(interval=10))
plt.xlim('2020-03-06','2020-12-31')
plt.ylim((0,50))
plt.savefig('03_clean_tweet_count_by_month_2020.tiff', dpi=300, format='tiff', bbox_inches='tight')

结果enter image description here


2条回答

如果没有要测试的数据,我不能确定,但是如果数据帧的行没有正确排序,您可能会得到这样的输出。尝试:

data.sort_values('date', inplace=True)
plt.plot(data['date'],data['count'])
plt.setp(plt.gca().xaxis.get_majorticklabels(),rotation=45)
plt.gca().xaxis.set_major_locator(mdates.DayLocator(interval=10))
plt.xlim('2020-03-06','2020-12-31')
plt.ylim((0,50))
plt.savefig('03_clean_tweet_count_by_month_2020.tiff', dpi=300, format='tiff', bbox_inches='tight')

在打印之前,首先尝试按日期列对DF进行排序

data=data.sort_values(by=['date'])
plt.plot(data['date'],data['count'])

相关问题 更多 >