pandas plotting time serires

时间:2018-09-18 19:58:48

标签: pandas matplotlib

Trying to plot YYYY:MM:DD HH:MM:SS on the x-axis with values on the Y.

the 'df = xxxx' is

         tagName   tagValue            tagTimestamp
0   Oil Pressure  52.512268 2018-09-17 12:20:03.099
1   Oil Pressure  52.443478 2018-09-17 12:20:02.598
2   Oil Pressure  48.912914 2018-09-17 12:20:02.348
4   Oil Pressure  45.463978 2018-09-17 12:20:01.848
5   Oil Pressure  50.580151 2018-09-17 12:20:01.598
6   Oil Pressure  49.411255 2018-09-17 12:20:01.348
8   Oil Pressure  48.072506 2018-09-17 12:20:01.146

running df.plot(kind='scatter',x='tagTimestamp', y='tagvalue', color='red') returns the error ValueError: scatter requires x column to be numeric I would like to keep the entire date time in the x column. I've reviewed all of the stack post closely related to this topic but have been unable to successfully convert this and plot it.

df.dtypes:

tagName                 object
tagValue               float64
tagTimestamp    datetime64[ns]
dtype: object 

2 个答案:

答案 0 :(得分:3)

This works for me, is this what you are after?

import pandas as pd

data.dtypes

Gives:

tagValue               float64
tagTimestamp    datetime64[ns]
dtype: object

Here is the data:

tagValue            tagTimestamp
0  52.512268 2018-09-17 12:20:03.099
1  52.443478 2018-09-17 12:20:02.598
2  48.912914 2018-09-17 12:20:02.348
3  45.463978 2018-09-17 12:20:01.848
4  50.580151 2018-09-17 12:20:01.598
5  49.411255 2018-09-17 12:20:01.348
6  48.072506 2018-09-17 12:20:01.146

And then plotting as a line chart, rather than a scatter:

data.plot(x = 'tagTimestamp')

Gives:

enter image description here

答案 1 :(得分:0)

您可以改用matplotlib的scatter

plt.scatter(df["tagTimestamp"].values, df["tagValue"].values)

完整示例:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

t = ["2018-09-17 12:20:03.099", "2018-09-17 12:20:02.598", "2018-09-17 12:20:02.348", "2018-09-17 12:20:01.848",
     "2018-09-17 12:20:01.598", "2018-09-17 12:20:01.348", "2018-09-17 12:20:01.146"]

df = pd.DataFrame({"time" : t, "value" : np.random.rand(len(t))})
df["time"] = pd.to_datetime(df["time"])

print(df.dtypes)   # time     datetime64[ns]
                   # value           float64
                   # dtype: object

plt.scatter(df["time"].values, df["value"], color="red")