Glen Veigas
Glen Veigas

Reputation: 194

How to plot a timeline graph of dictionary values containing a list of datetime objects on x-axis using matplotlib?

I have a dictionary containing social media apps as keys and a list of datetime.time() objects as values, I want to plot the datetime.time() objects on the x-axis, with the keys on the y-axis

here is the dictionary

{{'Instagram': [datetime.time(4, 28, 5, 322902),datetime.time(6, 29, 7, 122295),datetime.time(6, 30, 8, 885536),datetime.time(7, 31, 10, 637131datetime.time(7, 36, 19, 449087)]},
{'Twitter':[datetime.time(5, 37, 21, 179529),datetime.time(5, 38, 22, 942552),datetime.time(20, 13, 31, 629529),datetime.time(20, 14, 33, 387693)]},
{'Facebook':[datetime.time(17, 15, 35, 188039),datetime.time(19, 16, 36, 955703),datetime.time(20, 13, 31, 629529),datetime.time(21, 14, 33, 387693)]}}

And I want to plot a graph like this enter image description here

I want it to look like this though the dictionary contains a lot of data, this is just an example for the sake of representation

Upvotes: 0

Views: 312

Answers (1)

odion ferrao
odion ferrao

Reputation: 36

from datetime import time
import datetime
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter

d ={'Instagram': [time(4, 28, 5, 322902),time(6, 29, 7, 122295),time(6, 30, 8, 885536),time(7, 31, 10, 637131),time(7, 36, 19, 449087)],
'Twitter':[time(5, 37, 21, 179529),time(5, 38, 22, 942552),time(20, 13, 31, 629529),time(20, 14, 33, 387693)],
'Facebook': [time(17, 15, 35, 188039),time(19, 16, 36, 955703),time(20, 13, 31, 629529),time(21, 14, 33, 387693)]}

xpoints=[]
ypoints=[]
for x in d:
    for y in d[x]:
        xpoints.append(y)
        ypoints.append(x)
x_dt = [datetime.datetime.combine(datetime.date.today(), t) for t in xpoints]
fig, ax = plt.subplots()
plt.plot([],[])
ax.scatter(x_dt,ypoints)

myFmt = DateFormatter('%H')
ax.xaxis.set_major_formatter(myFmt)
fig.autofmt_xdate()[enter image description here][1]

enter image description here

Upvotes: 2

Related Questions