计划工时与实际工时的matplotlib barh

2024-04-19 04:11:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图为员工建立一个水平条形图,显示他们的计划工作时间与他们在给定日期的实际工作时间。你知道吗

我尝试了下面的代码,但正如你在下面的“绘图”图像中看到的,它将实际工作时间(蓝色)与计划工作时间(绿色)的末尾连接起来。而且x轴上的时间也不是很能说明问题。你知道吗

我想要的是为每个员工设置两个条形图,一个绿色的条形图在顶部显示计划的工作时间,一个蓝色的条形图在下面显示实际的工作时间,就像甘特图一样。有人能帮我理解我的代码哪里出错了吗?你知道吗

#import stack
import pandas as pd
import datetime as dt
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

#dummy df
df = pd.DataFrame([['Bob', '2018-09-14 9:00:00', '2018-09-14 18:00:00', 'actual']
                   , ['Bob', '2018-09-14 9:15:00', '2018-09-14 18:30:00', 'scheduled']
                   , ['Kim', '2018-09-14 9:00:00', '2018-09-14 18:00:00', 'actual']
                   , ['Kim', '2018-09-14 8:45:00', '2018-09-14 17:30:00', 'scheduled']]
                   , columns=['name','start','finish', 'type'])

#convert timestamp columns to datetime
df[['start', 'finish']] = df[['start', 'finish']].apply(pd.to_datetime)

#scheduled time period
scheduledStart = mdates.date2num(df['start'][(df['type'] == 'scheduled')].dt.to_pydatetime())
scheduledEnd =  mdates.date2num(df['finish'][(df['type'] == 'scheduled')].dt.to_pydatetime())
scheduledWidth = scheduledEnd - scheduledStart

#actual time period
actualStart = mdates.date2num(df['start'][(df['type'] == 'actual')].dt.to_pydatetime())
actualEnd =  mdates.date2num(df['finish'][(df['type'] == 'actual')].dt.to_pydatetime())
actualWidth = actualEnd - actualStart

#y axis values
yval = df['name'].unique()

#generate plot
fig, ax = plt.subplots()
ax.barh(yval, width = actualWidth, left = actualStart, color = 'blue', height = 0.3, label = 'actual')
ax.barh(yval, width = scheduledWidth, left = scheduledStart, color = 'green', height = 0.3, label = 'scheduled')

#format x axis to time of day
xfmt = mdates.DateFormatter('%H:%m')
ax.xaxis.set_major_formatter(xfmt)

# autorotate the dates
fig.autofmt_xdate()
plt.show()

figure


Tags: toimportdfastype时间dtstart
1条回答
网友
1楼 · 发布于 2024-04-19 04:11:09

尝试不同的值,例如第一个值为[0, 1],第二个值为[0.3, 1.3](这样它们就不会重叠)。我们只是移动height值。你知道吗

ax.barh([0, 1], width = actualWidth, left = actualStart, color = 'blue', height = 0.3, label = 'actual')
ax.barh([0.3, 1.3], width = scheduledWidth, left = scheduledStart, color = 'green', height = 0.3, label = 'scheduled')

并更改yticks(选择两条线之间的中心):

plt.yticks([0.15, 1.15], yval)

最后要修复xtick

fig.autofmt_xdate(ha='center')

example_figure

相关问题 更多 >