【问题标题】:Plot Timeline in Python在 Python 中绘制时间线
【发布时间】:2021-07-15 09:22:26
【问题描述】:

我有一个由 2 列组成的 pandas 数据框:日期和事件

我需要使用日期沿时间线绘制事件,但不知道如何在 python 中执行此操作。有人可以指导我吗?

我的数据框看起来像这样:

日期 |事件

2015-08-17 11:05:00 |生日

2017-04-10 09:10:02 |第一步

【问题讨论】:

  • 您是否尝试在谷歌上搜索可用于此类事情的库?
  • 我尝试过使用 Matplotlib,但没有成功
  • 您应该展示您的尝试,并针对您遇到的问题提出具体问题。

标签: python


【解决方案1】:

检查一下: https://matplotlib.org/stable/gallery/lines_bars_and_markers/timeline.html

基本上是这样的:

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

df = pd.DataFrame(
    {
        'event': ['birthday', 'first steps'] * 5,
        'date': pd.date_range(start='1/1/2018', periods=10)        
    }
)

df['date'] = pd.to_datetime(df['date'])

levels = np.tile(
    [-5, 5, -3, 3, -1, 1],
    int(np.ceil(len(df)/6))
)[:len(df)]

fig, ax = plt.subplots(figsize=(12.8, 4), constrained_layout=True);
ax.set(title="A series of events")

ax.vlines(df['date'], 0, levels, color="tab:red");  # The vertical stems.
ax.plot(   # Baseline and markers on it.
    df['date'],
    np.zeros_like(df['date']),
    "-o",
    color="k",
    markerfacecolor="w"
);

# annotate lines
for d, l, r in zip(df['date'], levels, df['event']):
    ax.annotate(
        r,
        xy=(d, l),
        xytext=(-3, np.sign(l)*3),
        textcoords="offset points",
        horizontalalignment="right",
        verticalalignment="bottom" if l > 0 else "top"
    );

# format xaxis with 4 month intervals
ax.xaxis.set_major_locator(mdates.MonthLocator(interval=4));
ax.xaxis.set_major_formatter(mdates.DateFormatter("%b %Y"));
plt.setp(ax.get_xticklabels(), rotation=30, ha="right");

# remove y axis and spines
ax.yaxis.set_visible(False);
ax.yaxis.set_visible(False);
ax.spines["left"].set_visible(False)
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)    
ax.margins(y=0.1);
plt.show();

【讨论】:

  • 你是如何从日期时间中剥离时间的?目前我的时间是一个 Timestamp 对象,这会导致错误。你会如何解决这个问题?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-02-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-21
  • 2018-08-24
相关资源
最近更新 更多