在 python / matplotlib 中创建简单的时间线图?

问题描述 投票:0回答:2

我正在尝试在 python 中创建时间轴。但是,我以前从未这样做过,到目前为止,寻找答案对我帮助不大。

基本上,我正在尝试重新创建类似于下面发布的图片的东西。

有没有人可以提供任何相关资源来帮助解决这个问题?或者,有谁知道如何编写类似于图像中所示内容的代码?

enter image description here

python matplotlib timeline
2个回答
0
投票

您可以使用 plotly 将图形绘制为甘特图。

import plotly.express as px
import pandas as pd

df = pd.DataFrame([
    dict(Task="Inflow", Start='2019-01-01', Finish='2023-01-01'),
    dict(Task="Cancelling", Start='2023-01-01', Finish='2059-01-01'),
    dict(Task="Outflow", Start='2059-01-01', Finish='2060-01-01')
])

fig = px.timeline(df, x_start="Start", x_end="Finish", y="Task")
fig.update_yaxes(autorange="reversed") # otherwise tasks are listed from the bottom up
fig.show()

这段代码输出:

如果您更喜欢坚持使用 matplotlib,那么您可以使用 axhspan 创建从一个日期到另一个日期的水平线或矩形。


0
投票

这是 matplotlib 可以做的事

annotate
+
text

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure(figsize=(7, 3))
ax = fig.add_subplot()

xvalues = [0, 1, 2, 3, 4, 5]
xlabels = [r'$t_0 = 2019$', r'$t_0 = 2023$', r'$t_0 = 2048$', r'$t_0 = 2059$', r'$t_0 = 2060$', r'$t_0 = 2066$']
tickheight = 0.1

ax.annotate("", (4, 1), (5, 1), arrowprops={'arrowstyle':'<-', 'shrinkA': 0, 'shrinkB': 0})
ax.plot([4, 4], [1 - tickheight, 1 + tickheight], c='k', lw=1)
ax.plot([5, 5], [1 - tickheight, 1 + tickheight], c='k', lw=1)
ax.text(4.5, 1.1, 'outflow', ha='center', va='baseline')

ax.annotate("", (2, 2), (4, 2), arrowprops={'arrowstyle':'<-', 'shrinkA': 0, 'shrinkB': 0})
ax.plot([2, 2], [2 - tickheight, 2 + tickheight], c='k', lw=1)
ax.plot([4, 4], [2 - tickheight, 2 + tickheight], c='k', lw=1)
ax.text(3, 2.1, 'cancelling', ha='center', va='baseline')

ax.annotate("", (1, 3), (3, 3), arrowprops={'arrowstyle':'<-', 'shrinkA': 0, 'shrinkB': 0})
ax.plot([1, 1], [3 - tickheight, 3 + tickheight], c='k', lw=1)
ax.plot([3, 3], [3 - tickheight, 3 + tickheight], c='k', lw=1)
ax.text(2, 3.1, 'inflow', ha='center', va='baseline')

ax.spines['top'].set_visible(False)
ax.spines['left'].set_visible(False)
ax.spines['right'].set_visible(False)

ax.set_xticks(xvalues)
ax.set_xticklabels(xlabels)

plt.xlim(-0.1, 5.1)
plt.ylim(0, 3.5)

plt.yticks([])

plt.tight_layout()

plt.show()

Result looks like this

© www.soinside.com 2019 - 2024. All rights reserved.