python - 字典中的甘特图,将离散的非连续日期列表作为值
问题描述
我正在尝试在 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 轴上的日期将是从字典中任何列表中出现的最早日期到最新日期的连续范围。
解决方案
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()
推荐阅读
- ios - 本地主机上的开发 node.js 服务器在 swiftUI 应用程序中返回 nil,但在浏览器中不返回
- python - 如何将具有不同数字的小时/分钟列转换为 python/pandas 中的日期时间对象?
- vim - 是否可以在 vim 缩写 id 中包含回车?
- r - 如何为对数正态分布列绑定蒙特卡罗模拟结果?
- sql - 使用 SQL 请求复制行和编辑值,但需要改进一下
- php - 在前端监控 PHP 执行的正确方法是什么?
- html - 如何从 Nokogiri 返回选择的短语
- python - Google Drive API / 将文件属性存储为数字而不是字符串
- python - 如何使用一个数据集来模拟另一个使用 Python 的数据集?
- spring-boot - Spring Boot 项目如何生成发行说明?