python - matplotlib 的日期时间问题

标签 python matplotlib

我正在用 matplotlib 来显示一系列数据。

我正在使用 python 2.7。 我有一个带有日期的 pandas Dataframe。我将日期转换为日期时间,并且尝试显示绘图但没有成功。

import pandas as pd
import matplotlib.pyplot as plt
from datetime import datetime, date

#I imported df before

type(df)
<class 'pandas.core.frame.DataFrame'>

# The dataframe
AnneeObs  MoisObs  JourObs  NbFluxEntrant
0        2019        8       19            763
1        2019        8        1           1098
...        ...      ...      ...            ...
655      2017       11        1            428
656      2017       11       13           1530

[657 rows x 4 columns]

# To convert dates to datetime
for i in range(0,len(df)):
     df.loc[i,"dateObs"] = date(year=df.iloc[i,0], month=df.iloc[i,1], 
day=df.iloc[i,2])

df['dateObs'] = pd.DatetimeIndex(df['dateObs'])

# To order by dates
df = df.sort_values("dateObs", ascending=True)

df2 = df[["dateObs", "NbFluxEntrant"]]

df2bis = df2.copy()
df2bis = df2bis.set_index('dateObs')

df2bis

# The new dataframe
            NbFluxEntrant
dateObs                  
2017-11-01            428
2017-11-02            931
...                   ...
2019-08-18            243
2019-08-19            763

[657 rows x 1 columns]

# Maybe it's too much...
df2bis.index = pd.to_datetime(df2bis.index)

type(df2bis.index)
<class 'pandas.core.indexes.datetimes.DatetimeIndex'>

# I tried to display it but...
df2bis.plot()

但是,它不起作用:

Fail to execute line 1: df2bis.plot()
ValueError: view limit minimum 0.0 is less than 1 and is an invalid Matplotlib date value. This often happens if you pass a non-datetime value to an axis that has datetime units

我尝试了其他代码,但没有什么好处:

df2bis.plot(x="dateObs", y="NbFluxEntrant")
df2bis.plot(x=df2bis.index.values, y="NbFluxEntrant")

你有什么建议吗?

提前致谢

编辑: 我尝试了另一个不起作用的代码:

import matplotlib

dates = matplotlib.dates.date2num(df2bis.index)
dates

array([736634., 736635.,..., 737289., 737290.])

matplotlib.pyplot.plot_date(dates, df2bis["NbFluxEntrant"])

ValueError: view limit minimum 0.0 is less than 1 and is an invalid Matplotlib date value. This often happens if you pass a non-datetime value to an axis that has datetime units

嗯...

最佳答案

我也遇到过类似的问题。你可以试试这个:

df2bis.set_index('dateObs', inplace=True)
df2bis.index = pd.to_datetime(df2bis.index)
df2bis.plot()

关于python - matplotlib 的日期时间问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57607183/

相关文章:

python - python中条件概率问题的模拟

python - 在不使用 xticks 的情况下设置二维等高线图的轴值

python - matplotlib 需要 pyparsing

python - 如何使用 python 在图形中添加标记,如下所示?

python - BeautifulSoup 第 n 个类型返回空列表。 Soup.select()[n -1] 返回元素。为什么?

python - 如何通过将大于 2 GiB 的文件分割成更小的片段来 pickle 它们

python - 使用 matplotlib 在网络中设置动态节点形状

python - Matplotlib 不在 virtualenv 中显示图形

python - 即时生成字典键

python - 通过字典值之一的索引将字典拆分为多个字典