【问题标题】:How can I include 2 specific dates and ticks when plotting Timestamps?绘制时间戳时如何包含 2 个特定日期和刻度?
【发布时间】:2016-03-03 13:15:45
【问题描述】:

当我从 csv 文件中读取数据时,我使用 pd.to_datetime(df.date) 将日期信息从字符串转换为 pandas.tslib.Timestamp。从这里,我可以绘制数据,并得到如下内容:

我有两个问题:

  1. 日期必须轮换,这是骗人的。看起来这个巨大的峰值似乎发生在 2014 年 12 月,而实际上,它发生在次年 2 月。
  2. 大幅飙升的日期相对重要,而其他日期(2014 年 12 月除外)则不重要。

我想:

  1. 能够在月份下方写下年份,以便更节省空间,或在 x 轴上添加刻度,以便 xticks 指向的位置明确。
  2. 对我的 xticks 更加保守,并确保始终将 2014 年 12 月和 2015 年 2 月包含为 ticks。

我知道 pandas 不能很好地使用 Matplotlib 日期功能。如何在不必切换到 numpy 数组的情况下完成我想要的?

我的代码:

import pandas as pd
import matplotlib.pyplot as plt
import datetime as dt
import numpy as np
import seaborn as sns


palette = sns.color_palette()

plt.close('all')

s = pd.read_csv('all_tweets.csv')

t = pd.to_datetime(s.date)

fig = plt.figure(1)
ax = plt.gca()

plt.grid('off')
ax.set_axis_bgcolor('white')
ax.axhline(0, color = 'k')
ax.axvline(min(t), color = 'k')
plt.xlim([min(t), max(t)])







plt.plot(t,s.tweet, color = 'k', linewidth = 10, linestyle = '-', label = 'Tweets')

smoothed = pd.ewma(s.tweet, span = 20, adjust = False)
l, = plt.plot(t,smoothed, color = 'r', linewidth = 5, linestyle = '--',label = 'Smoothed')
l.set_dashes([10,6])
plt.xticks(fontsize = 30, rotation = 45)
plt.yticks(fontsize = 30)



plt.xlabel('Date', fontsize = 36,labelpad = 25)
plt.ylabel('Tweets Per Day', fontsize = 36,labelpad = 25)



figManager = plt.get_current_fig_manager()
figManager.window.showMaximized()
plt.savefig("all_tweets.png",bbox_inches='tight')

【问题讨论】:

  • 您是否有一些示例数据可以重现您的问题?我试图复制它,但索引打印得很好。
  • 我要提一下,这个数据只针对黑色曲线。我特意轮换了日期以便阅读。

标签: python date datetime pandas matplotlib


【解决方案1】:

这不是答案,但我需要这样发布,以便您查看图形。鉴于上面链接中的数据和以下转换,这是我的图表:

df = pd.read_csv(file_location...)
df.set_index('date', inplace=True)
df.index = pd.to_datetime(df.index)
df.plot()

【讨论】:

  • 甜蜜,这几乎正是我想要的。现在,如何将 2015 年 2 月和 2014 年 12 月添加到 ticls 中
猜你喜欢
  • 1970-01-01
  • 2011-12-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-16
相关资源
最近更新 更多