Reputation: 382
I'm trying to create one horizontal bar graph with stacked datetimes in python using matplotlib and pandas. It should represent a timeline, when a machine was available (green) and when not (red). In the end it should look like this:
I'm not sure whether to use barh or if there is a simpler solution for this.
My approach was like this, but I get a TypeError: invalid type promotion
import datetime
import matplotlib.dates as mdates
time = datetime.datetime.now()
data = [[time,time+datetime.timedelta(0,5),time+datetime.timedelta(0,10)]]
#data_num = [[1,2,3]]
df2 = pd.DataFrame(data)
df2.plot.barh(stacked=True);
Upvotes: 2
Views: 565
Reputation: 46978
I don't think you can use a stacked barplot for that. One way out is to make a very thick line plot. Ideally you should have like a dateframe that indicates the time interval when it's off or on:
import datetime
import pandas as pd
import matplotlib.pyplot as plt
time = datetime.datetime.now()
date_from = [time,time+datetime.timedelta(0,30),
time+datetime.timedelta(0,50)]
date_to = date_from[1:] + [time+datetime.timedelta(0,100)]
df = pd.DataFrame({'date_from':date_from,'date_to':date_to,
'status':[0,1,0]})
df
date_from date_to status
0 2021-11-28 12:30:39.428099 2021-11-28 12:31:09.428099 0
1 2021-11-28 12:31:09.428099 2021-11-28 12:31:29.428099 1
2 2021-11-28 12:31:29.428099 2021-11-28 12:32:19.428099 0
Then iterate through the rows and plot:
cols = ['#DADDFC','#FC997C']
fig,ax = plt.subplots(figsize = (8,3))
for i in range(df.shape[0]):
ax.plot([df['date_from'][i],df['date_to'][i]],[1,1],
linewidth=50,c=cols[df['status'][i]])
ax.set_yticks([])
ax.set_yticklabels([])
ax.set(frame_on=False)
Upvotes: 3