Python 在 matplotlib 中绘制熊猫日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25416955/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:11:52  来源:igfitidea点击:

Plot pandas dates in matplotlib

pythonpandasdatetimedataframematplotlib

提问by Gerhard

I have a fixed-width data file containing dates, but when I try to plot the data the dates are not displayed properly on the x-axis.

我有一个包含日期的固定宽度数据文件,但是当我尝试绘制数据时,x 轴上的日期显示不正确。

My files looks like

我的文件看起来像

2014-07-10 11:49:14.377102    45
2014-07-10 11:50:14.449150    45
2014-07-10 11:51:14.521168    21
2014-07-10 11:52:14.574241     8
2014-07-10 11:53:14.646137    11
2014-07-10 11:54:14.717688    14

etc

等等

and I use pandasto read in the file

我用熊猫读入文件

#! /usr/bin/env python
import pandas as pd
import matplotlib.pyplot as plt
data = pd.read_fwf('myfile.log',header=None,names=['time','amount'],widths=[27,5])
data.time = pd.to_datetime(data['time'], format='%Y-%m-%d %H:%M:%S.%f')
plt.plot(data.time,data.amount)
plt.show()

So I suppose the issue here is conversion from pandas to matplotlib datetime, How would one do a conversion?

所以我想这里的问题是从 Pandas 到 matplotlib datetime 的转换,如何进行转换?

I also tried with pandas directly:

我也直接尝试过熊猫:

data.time = pd.to_datetime(data['time'], format='%Y-%m-%d %H:%M:%S.%f')
data.set_index('time') # Fails!!
data.time.plot()

but this fails with

但这失败了

TypeError: Empty 'Series': no numeric data to plot

类型错误:空“系列”:没有要绘制的数字数据

采纳答案by Osmond Bishop

If you use a list containing the column name(s) instead of a string, data.set_index will work

如果您使用包含列名而不是字符串的列表,则 data.set_index 将起作用

The following should show the dates on x-axis:

以下应显示 x 轴上的日期:

#! /usr/bin/env python
import pandas as pd
import matplotlib.pyplot as plt
data = pd.read_fwf('myfile.log',header=None,names=['time','amount'],widths=[27,5])
data.time = pd.to_datetime(data['time'], format='%Y-%m-%d %H:%M:%S.%f')
data.set_index(['time'],inplace=True)
data.plot()

#OR 
plt.plot(data.index, data.amount)