字典中的甘特图,以离散的非连续日期列表作为值 [英] Gantt Chart from dictionary with lists of discrete non-contiguous dates as values

查看:61
本文介绍了字典中的甘特图,以离散的非连续日期列表作为值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Python中建立甘特图(与所使用的软件包无关...也许是Plotly?),其中X轴将是离散日期(例如2020-01-01、2020-01-02,...),Y轴将成为名称(例如,"A","B",...).每个名称的日期列表不一定是连续的.它们当前采用以下格式:

I'm trying to build a Gantt chart in Python (indifferent to package used... perhaps Plotly?) where the X-axis will be discrete dates (e.g., 2020-01-01, 2020-01-02, ...) and the Y-axis will be names (e.g., 'A', 'B', ...). The lists of dates per name aren't necessarily contiguous. They are currently in the following format:

names_dict = {
              'A': ['2020-01-01', '2020-01-02', '2020-01-31'], 
              'B': ['2020-01-03'], 
              'C': ['2020-01-01', '2020-01-02', '2020-01-03', '2020-01-04'],
              ...
              }

是否有一种简便的方法可以从字典中以这种格式构建甘特型图表?理想情况下,它将是一个网格,并且对于X轴上的每个日期,给定名称的正方形将为白色或红色(表示该名称的日期列表中存在该日期).因此,X轴上的日期是从字典中任何列表中出现的最早日期到最新日期的连续范围.

Is there an easy way to build a Gantt-type chart from a dictionary in this format? Ideally it would be a grid, and for each date on the X-axis the square for a given name would either be white or red (indicating the presence of that date in the list of dates for that name). Thus, the dates on the X-axis would be the continuous range from the earliest date present in any list in the dictionary to the latest date.

推荐答案

以下是将给定数据与matplotlib的水平线( barh )结合使用的示例.字典以相反的顺序遍历字典,因为matplotlib从底部开始绘制它们.

Here is an example using the given data with matplotlib's horizontal bars (barh). The dictionary is traversed in reverse order of the keys, as matplotlib draws them starting at the bottom.

Matplotlib允许在情节的各个方面进行无数的周工作.

Matplotlib allows a myriad of tweeking, for every aspect of the plot.

from matplotlib import pyplot as plt
import matplotlib.dates as mdates
from datetime import datetime

names_dict = {'A': ['2020-01-01', '2020-01-02', '2020-01-31'],
              'B': ['2020-01-03'],
              'C': ['2020-01-01', '2020-01-02', '2020-01-03', '2020-01-04'] }

# x_min = min([datetime.fromisoformat(d) for dates in names_dict.values() for d in dates])

fig, ax = plt.subplots(figsize=(12,4))
for name in reversed(list(names_dict.keys())):
    for d in names_dict[name]:
        ax.barh(name, width=1.0, left=mdates.date2num(datetime.fromisoformat(d)),
                height=1.0, color='crimson', align='center')
for i in range(len(names_dict)+1):
    ax.axhline(i-0.5, color='black')

ax.xaxis_date()
ax.xaxis.set_minor_locator(mdates.DayLocator(interval=1))
ax.xaxis.set_major_locator(mdates.DayLocator(interval=5))
ax.xaxis.set_major_formatter(mdates.DateFormatter("%b %d"))
# ax.grid(True, axis='x') # to show vertical gridlines at each major tick
ax.autoscale(enable=True, axis='y', tight=True)
plt.show()

这篇关于字典中的甘特图,以离散的非连续日期列表作为值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆