Matplotlib-时间序列分析Python

问题描述 投票:0回答:2

我正在尝试使用此数据(https://gist.github.com/datomnurdin/33961755b306bc67e4121052ae87cfbc)创建2种时间序列。首先,每天有多少计数。每天第二个总情绪。

每天第二个总情绪代码。

import matplotlib.pyplot as plt
import pandas as pd

df = pd.read_csv('data_filtered.csv', parse_dates=['date'], index_col='date')

def plot_df(df, x, y, title="", xlabel='Date', ylabel='Value', dpi=100):
    plt.figure(figsize=(16,5), dpi=dpi)
    plt.plot(x, y, color='tab:red')
    plt.gca().set(title=title, xlabel=xlabel, ylabel=ylabel)
    plt.show()

plot_df(df, x=df.index, y=df.sentiment, title='Sentiment Over Time')

第二时间序列图对我来说似乎没有任何意义。也可以保存该图形以备将来参考。

enter image description here

python pandas matplotlib
2个回答
1
投票

尝试检查源数据。


日期

如果我尝试使用以下代码绘制date的分布:

import matplotlib.pyplot as plt
import pandas as pd

df = pd.read_csv('data_filtered.csv', parse_dates = ['date'])

df['date'].hist()
plt.show()

我得到:

enter image description here

如您所见,大多数date值都集中在2020-05-192020-05-30周围,中间没有任何值。因此,仅在图形的左侧和右侧而不是在中间看到点是有意义的。


观点

如果我尝试使用以下代码绘制sentiment的分布:

import matplotlib.pyplot as plt
import pandas as pd

df = pd.read_csv('data_filtered.csv', parse_dates = ['date'])

df['sentiment'].hist()
plt.show()

我得到:

enter image description here

如您所见,sentiment值集中在三组中:-101;没有其他价值。因此,仅在图形的底部,中心和顶部看到点是有意义的,在其他任何地方都看不到。


散点图

最后,我尝试在散点图中组合datesentiment

import matplotlib.pyplot as plt
import pandas as pd

df = pd.read_csv('data_filtered.csv', parse_dates = ['date'])

fig, ax = plt.subplots(1, 1, figsize = (16, 5))

ax.plot(df['date'], df['sentiment'], 'o', markersize = 15)
ax.set_title('Sentiment Over Time')
ax.set_xlabel('Date')
ax.set_ylabel('Value')

plt.show()

我得到:

enter image description here

正是您的图形,但是这些点不是通过线连接的。您可以看到这些值如何集中在特定区域中而不分散。


累积

如果要通过sentiment汇总date值,请检查此代码:

import matplotlib.pyplot as plt
import pandas as pd

df = pd.read_csv('data.csv', parse_dates = ['date'])

df_cumulate = df.groupby(['date']).sum()

def plot_df(df, x, y, title="", xlabel='Date', ylabel='Value', dpi=100):
    plt.figure(figsize=(16,5), dpi=dpi)
    plt.plot(x, y, color='tab:red')
    plt.gca().set(title=title, xlabel=xlabel, ylabel=ylabel)
    plt.show()

plot_df(df_cumulate, x=df_cumulate.index, y=df_cumulate.sentiment, title='Sentiment Over Time')

我通过df = pd.read_csv('data.csv', parse_dates = ['date'])行汇总数据;这里是sentiment随时间累积的图:

enter image description here


0
投票

您链接到的数据有八个单独的日期。

如果您只是简单地复制/粘贴,则日期不解释为时间点,而是字符串。

您可以通过转换为日期时间对象来更改它:

#convert to datetime
df['date'] = pd.to_datetime(df['date'])

整个图上的连接来自以下事实:一个数据点的索引确定了何时,但它的x坐标值(此处为:日期)确定了where 。由于plt.plot是一种连接数据点的方法,因此,一个接一个地绘制的数据点将用一条线连接,而不管它们在哪里结束。您可以通过对数据进行排序来对齐时间点和位置:

#then sort by date
df.sort_values(by='date', inplace=True)

这并不能构成一个容易解释的情节,但是现在至少您知道什么线是从哪里来的:

enter image description here

一种更好的数据绘制方式是堆叠条形图:

a=df.groupby(['date', 'sentiment']).agg(len).unstack()
a.columns = ['-1', '0', '1']
a[['-1', '0', '1']].plot(kind='bar', stacked=True)

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.