在PyPlot中绘制日期时遇到麻烦

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

我想绘制一个简单的时间序列。这是我的代码:

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from datetime import datetime
%matplotlib inline

df = pd.read_csv("sample.csv", parse_dates=['t'])
df[['sq', 'iq', 'rq']] = df[['sq', 'iq', 'rq']].apply(pd.to_numeric, errors='coerce')
df = df.fillna(0)
df.set_index('t')

这是输出的一部分:

Output2

df[['t','sq']].plot()
plt.show()

First Plot

如您所见,上图中的x轴不是我想要显示的日期。当我改变如下的绘图调用时,我得到以下乱码图,尽管x轴现在是正确的。

df[['t','sq']].plot(x = 't')
plt.show()

Second Plot

关于我做错了什么的提示?如果您需要有关该问题的更多信息,请发表评论并告诉我们。提前致谢。

python pandas matplotlib
2个回答
1
投票

我认为你的问题是虽然你已经解析了t列,但它不是日期时间类型。请尝试以下方法:

# Set t to date-time and then to index
df['t'] = pd.to_datetime(df['t'])
df.set_index('t', inplace=True)

阅读你的评论和你添加的答案可能会得出结论,这种问题只能通过在pd.read_csv()中指定解析器来解决。所以这证明我的解决方案原则上是有效的。查看您发布的问题,代码的另一个问题是您指定plot命令的方式。一旦t成为索引,您只需要为plot命令选择除t之外的列。

import pandas as pd
import matplotlib.pyplot as plt

# Read data from file
df = pd.read_csv('C:\\datetime.csv', parse_dates=['Date'])

# Convert Date to date-time and set as index
df['Date'] = pd.to_datetime(df['Date'])
df.set_index('Date', inplace=True)

df.plot(marker='D')
plt.xlabel('Date')
plt.ylabel('Number of Visitors')
plt.show()


df
Out[37]: 
        Date  Adults  Children  Seniors
0 2018-01-05     309       240      296
1 2018-01-06     261       296      308
2 2018-01-07     273       249      338
3 2018-01-08     311       250      244
4 2018-01-08     272       234      307

df
Out[39]: 
            Adults  Children  Seniors
Date                                 
2018-01-05     309       240      296
2018-01-06     261       296      308
2018-01-07     273       249      338
2018-01-08     311       250      244
2018-01-08     272       234      307

enter image description here


0
投票

如上面的答案所指出的,问题是对日期的解析不正确。然而,它的解决方案是将date_parser传递给read_csv方法调用:

from datetime import datetime as dt
dtm = lambda x: dt.strptime(str(x), "%Y-%m-%d")    
df = pd.read_csv("sample.csv", parse_dates=['t'], infer_datetime_format = True, date_parser= dtm)
© www.soinside.com 2019 - 2024. All rights reserved.