使用工作时间绘制时间表

dbf7pr2w  于 2021-08-25  发布在  Java
关注(0)|答案(1)|浏览(365)

我正在使用pd.offset.custombusinesshour实现与工作时间(上午8点到下午5点)关联的时间表,并尝试使用matplotlib绘制甘特图或水平条形图。在这一点上,我想切断x轴在工作时间之外的间隔,这是不必要的。d日下午5点到d+1日上午8点之间似乎存在休息时间


我搜索了businesshour方法的参数配置,使用关键字“interval”、“spacing”设置勾号的方式,但找不到合适的解决方案。我考虑过使用matplotlib.dates模块的其他绘图方法,但结果是徒劳的。
这是我的python代码。

import pandas as pd
from datetime import datetime, date, timedelta, time
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import matplotlib.dates as mdates

num = 6

start_time = datetime(2021, 7, 7, 13, 5, 16, 268902)
int_to_time = pd.offsets.CustomBusinessHour(start="08:00", end="17:00", weekmask="1111111")

duration = num * int_to_time

horizon = [start_time + (i+1) * int_to_time for i in range(num+1)]
horizon = [i.replace(microsecond=0) for i in horizon]

fig, gnt = plt.subplots(figsize=(12,3))

gnt.barh(y=1, width=duration, left=start_time, color="cyan", height=0.2)

gnt.set_xticks(horizon)
gnt.set_xticklabels(horizon, rotation=90)

gnt.tick_params(bottom=False, labelbottom=False, top=True, labeltop=True)

plt.show()
xlpyo6sf

xlpyo6sf1#

您正在尝试开发甘特图,并且x轴标签的间距存在问题。您的x轴表示时间戳,您希望它们均匀分布(每小时一次)。
轴记号位置由记号定位器确定,标签由记号格式化程序确定。datetimes的默认记号定位器是autodateslocator,它可能实现hourlocator。这将返回对应于24小时日期时间轴的x和y值。
解决问题的一个方法是简单地使用linearlocator或fixedlocator以及fixedformatter。这使您可以非常直接地控制记号的位置和标签。
我必须补充的是,有很多教程和帖子都是关于如何使用matplotlib或plotly制作甘特图的,它们很容易搜索。我建议在开发绘图时查看其中一些。
解决方案在下面的代码上下文中实现。

import pandas as pd
from datetime import datetime, date, timedelta, time
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import matplotlib.dates as mdates

num = 6

start_time = datetime(2021, 7, 7, 13, 5, 16, 268902)
int_to_time = pd.offsets.CustomBusinessHour(start="08:00", end="17:00", weekmask="1111111")

duration = num * int_to_time

horizon = [start_time + (i+1) * int_to_time for i in range(num+1)]
horizon = [i.replace(microsecond=0) for i in horizon]

fig, gnt = plt.subplots(figsize=(12,3))

gnt.barh(y=1, width=duration, left=start_time, color="cyan", height=0.2)

gnt.xaxis.set_major_locator(ticker.LinearLocator(7))
gnt.xaxis.set_major_formatter(ticker.FixedFormatter(horizon))

gnt.tick_params(bottom=False, labelbottom=False, top=True, labeltop=True, rotation=90)

相关问题