如何在Matplotlib中绘制Thing分类轴对应的日期范围线段
绘制类别对应日期区间的线段图
数据准备
首先定义并处理数据:
import pandas as pd dt = pd.DataFrame.from_dict( { "thing": {0: "A", 1: "B", 2: "C"}, "min": { 0: "2021-11-01 00:00:00+00:00", 1: "2021-11-01 00:00:00+00:00", 2: "2021-11-01 00:00:00+00:00", }, "max": { 0: "2021-11-02 00:00:00+00:00", 1: "2021-11-05 00:00:00+00:00", 2: "2021-11-07 00:00:00+00:00", }, } ).assign( min=lambda x: pd.to_datetime(x["min"]), max=lambda x: pd.to_datetime(x["max"]), )
数据结构
处理后的数据结构如下:
| thing | min | max | |
|---|---|---|---|
| 0 | A | 2021-11-01 00:00:00+00:00 | 2021-11-02 00:00:00+00:00 |
| 1 | B | 2021-11-01 00:00:00+00:00 | 2021-11-05 00:00:00+00:00 |
| 2 | C | 2021-11-01 00:00:00+00:00 | 2021-11-07 00:00:00+00:00 |
可视化需求
需要生成满足以下要求的图表:
- X轴为日期
- Y轴对应
thing列的类别(A、B、C) - 每个类别对应一条水平线段,连接其
min和max日期
实现代码(Matplotlib)
使用Matplotlib可以快速实现该需求:
import matplotlib.pyplot as plt # 为每个类别分配Y轴位置 y_positions = {thing: idx for idx, thing in enumerate(dt["thing"])} # 创建画布 plt.figure(figsize=(10, 3)) # 遍历数据绘制每条水平线段 for _, row in dt.iterrows(): plt.hlines( y=y_positions[row["thing"]], xmin=row["min"], xmax=row["max"], color='#1f77b4', linewidth=3 ) # 设置坐标轴样式 plt.yticks(ticks=list(y_positions.values()), labels=list(y_positions.keys())) plt.xlabel("日期") plt.ylabel("类别") plt.title("类别对应的日期区间") plt.grid(axis='x', linestyle='--', alpha=0.7) # 调整布局 plt.tight_layout() plt.show()
这段代码会生成每个类别对应日期区间的水平线段图,Y轴显示类别名称,X轴展示日期范围,完全匹配需求。
内容的提问来源于stack exchange,提问作者baxx
相关产品推荐
相关产品推荐

