首页 > 解决方案 > 字典中的甘特图,将离散的非连续日期列表作为值

问题描述

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

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 轴上的日期将是从字典中任何列表中出现的最早日期到最新日期的连续范围。

标签: pythondictionaryplotlydata-visualizationgantt-chart

解决方案


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 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()

resulting plot


推荐阅读