0
   id        timestamp          energy
0   a   2012-03-18 10:00:00     0.034
1   b   2012-03-20 10:30:00     0.052
2   c   2013-05-29 11:00:00     0.055
3   d   2014-06-20 01:00:00     0.028
4   a   2015-02-10 12:00:00     0.069

I want to plot these data like below. just time on x-axis, not date nor datetime.

because I want to see the values per each hour.

https://i.sstatic.net/u73eJ.png

but this code plot like this.

plt.plot(df['timestamp'], df['energy'])

https://i.sstatic.net/yd6NL.png

I tried some codes but they just format the X data hide date part and plot like second graph.

+ df['timestamp'] is datetime type.

what should I do? Thanks.

1
  • 1
    try replacing df['timestamp'] with df['timestamp'].dt.time Commented May 6, 2020 at 7:37

2 Answers 2

0

you can convert your datetime into time, if your df["timestamp"] is already in datetime format then

df["time"] = df["timestamp"].map(lambda x: x.time())
plt.plot(df['time'], df['energy'])

if df["timestamp"] is of type string then you can add one more line in front as df["timestamp"] = pd.to_datetime(df["timestamp"])

Update: look like matplotlib does not accept time types, just convert to string

df["time"] = df["timestamp"].map(lambda x: x.strftime("%H:%M"))
plt.scatter(df['time'], df['energy'])
Sign up to request clarification or add additional context in comments.

2 Comments

I already tried converting date time to time df['timestamp'] = pd.to_datetime(df['timestamp]) df['time] = df['timestamp].dt.time like this. but when I plot, TypeError : float() argument must be a string or a number, not 'datetime.time' occurred even I tested with your answer code.
look like matplotlib does not allow "time" type, you can try convert df["time"] to string type by df["time"] = df["timestamp"].map(lambda x: x.strftime("%H:%M")) and try to plot again plt.scatter(df['time'], df['energy'])
0

First check, if type of df["timestamp"] is in datetime format. if not

import pandas as pd  
time = pd.to_datetime(df["timestamp"])
print(type(time))

Then,

import matplotlib.pyplot as plt
values = df['energy']
plt.plot_date(dates , values )
plt.xticks(rotation=45)
plt.show()

1 Comment

df['timestamp'] is already datetime type. and It still plot like second graph.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.