我正在尝试为员工构建一个水平条形图,显示他们的计划工作时间与特定日期的实际工作时间。
我已经尝试了以下代码,但正如您在下面的“绘图”图像中所看到的,它将实际工作时间(蓝色)连接到计划时间的末尾(绿色)。而且 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()
最佳答案
尝试不同的值,例如第一个值使用 [0, 1]
,第二个值使用 [0.3, 1.3]
ax.barh
(所以它们不重叠)。我们只是简单地改变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')
关于python - matplotlib barh 计划工作时间与实际工作时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52396650/