简体   繁体   English

显示日期时间区域的堆叠水平条

[英]Stacked horizontal bar showing datetime areas

I'm trying to create one horizontal bar graph with stacked datetimes in python using matplotlib and pandas.我正在尝试使用 matplotlib 和 pandas 在 python 中创建一个带有堆叠日期时间的水平条形图。 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.我不确定是否使用 barh 或者是否有更简单的解决方案。

My approach was like this, but I get a TypeError: invalid type promotion我的方法是这样的,但我得到一个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);

I don't think you can use a stacked barplot for that.我认为您不能为此使用堆叠的条形图。 One way out is to make a very thick line plot.一种方法是制作一条非常粗的线 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:然后遍历行和 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)

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM