python - matplotlib barh 计划工作时间与实际工作时间

标签 python python-3.x matplotlib gantt-chart

我正在尝试为员工构建一个水平条形图,显示他们的计划工作时间与特定日期的实际工作时间。

我已经尝试了以下代码,但正如您在下面的“绘图”图像中所看到的,它将实际工作时间(蓝色)连接到计划时间的末尾(绿色)。而且 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

最佳答案

尝试不同的值,例如第一个值使用 [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')

example_figure

关于python - matplotlib barh 计划工作时间与实际工作时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52396650/

相关文章:

python - 奇怪的行为 : pcolormesh and meshgrid (easy)

python:对具有相同第一个元素的元组的元素进行分组

string - 执行 pandas to_hdf 时出现错误消息 "Exception: cannot find the correct atom type"

python - XML 解析忽略文本

当使用 mpl_toolkits.axisartist.subplot 的紧凑布局时,matplotlib 颜色条会在正确的尺寸上创建一个大的空间

python - 如何在 scikit-learn 下绘制拟合高斯混合模型的概率密度函数?

python - 用于保存 Python 中数据记录的扩展数据的数据类型

python - 如何从 2D numpy 数组中删除第一行和最后一行和最后一列?

python pycharm依赖同步

python - 如何在 matplotlib 中的曲线末端放置一个箭头?