如何创建时间线图

huangapple go评论98阅读模式
英文:

How to create a timeline chart

问题

有人知道是否可以使用某个Python库创建这样的图表吗?如果可以,是否有任何示例可分享?

如何创建时间线图

英文:

Does anyone know if it's possible to create a graph like this, with some Python library? If so, does anyone have any examples to share?

如何创建时间线图

答案1

得分: 2

以下是翻译好的部分:

假设您的数据存储在一个“电子表格”中,为了更加灵活,您可以使用 [tag:matplotlib]:

import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter

fig, ax = plt.subplots(figsize=(10, 3))

ax.set_ylim(0, 1)
ax.set_yticklabels([])
ax.yaxis.set_ticks_position("none")

ax.set_xticks(df[["start", "end"]].stack().unique())
ax.xaxis.set_major_formatter(DateFormatter("%H:%M"))
ax.set_xlim(df["start"].min(), df["end"].max())
for label in ax.get_xticklabels():
    label.set_weight("bold")
    label.set_fontname("serif")

d = {"Status A": "#ff0000", "Status B": "#00b050", "Status C": "#0070c0"}

for s, c in d.items():
    tmp = df[df["status"] == s]
    ax.barh(tmp["y"], tmp["duration"], left=tmp["start"], height=0.2, color=d
展开收缩
)
rects = [plt.Rectangle((0, 0), 0, 0, color=c) for c in d.values()] ax.legend( rects, d.keys(), ncol=len(d.keys()), bbox_to_anchor=(0.463, 1.25), frameon=False, handleheight=2, handlelength=3, handletextpad=0.5, prop={"weight": "bold", "family": "serif"}, ) plt.grid(True) plt.tight_layout() plt.show();

输出:

如何创建时间线图

使用的输入:

状态 开始时间 结束时间
状态 A 12:00 12:45
状态 B 12:45 13:10
状态 C 13:10 13:40
状态 B 13:40 14:15
状态 A 14:15 14:40
状态 C 14:40 15:10
状态 A 15:10 15:45
状态 C 15:45 16:00
状态 B 16:00 16:30
#pip install pandas
import pandas as pd

df = pd.read_excel("file.xlsx")

df[["start", "end"]] = df[["start", "end"]].apply(pd.to_datetime, format="%H:%M") 
df["duration"] = df["end"] - df["start"]
df["y"] = 0.5 #虚构的数值 y 值
英文:

Assuming your data is held in a spreadsheet, for more flexibility, you can use [tag:matplotlib] :

import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter

fig, ax = plt.subplots(figsize=(10, 3))

ax.set_ylim(0, 1)
ax.set_yticklabels([])
ax.yaxis.set_ticks_position("none")

ax.set_xticks(df[["start", "end"]].stack().unique())
ax.xaxis.set_major_formatter(DateFormatter("%H:%M"))
ax.set_xlim(df["start"].min(), df["end"].max())
for label in ax.get_xticklabels():
    label.set_weight("bold")
    label.set_fontname("serif")

d = {"Status A": "#ff0000", "Status B": "#00b050", "Status C": "#0070c0"}

for s, c in d.items():
    tmp = df[df["status"] == s]
    ax.barh(tmp["y"], tmp["duration"], left=tmp["start"], height=0.2, color=d
展开收缩
) rects = [plt.Rectangle((0, 0), 0, 0, color=c) for c in d.values()] ax.legend( rects, d.keys(), ncol=len(d.keys()), bbox_to_anchor=(0.463, 1.25), frameon=False, handleheight=2, handlelength=3, handletextpad=0.5, prop={"weight": "bold", "family": "serif"}, ) plt.grid(True) plt.tight_layout() plt.show();

Output :

如何创建时间线图

Input used :

status start end
Status A 12:00 12:45
Status B 12:45 13:10
Status C 13:10 13:40
Status B 13:40 14:15
Status A 14:15 14:40
Status C 14:40 15:10
Status A 15:10 15:45
Status C 15:45 16:00
Status B 16:00 16:30
#pip install pandas
import pandas as pd

df = pd.read_excel("file.xlsx")

df[["start", "end"]] = df[["start", "end"]].apply(pd.to_datetime, format="%H:%M") 
df["duration"] = df["end"] - df["start"]
df["y"] = 0.5 #to fake numeric y-values

答案2

得分: 0

使用plotly.express.timeline应该非常简单。请查看该页面上的第一个示例。如果你希望它在一个y轴位置上,就像你的屏幕截图一样,那么可以尝试以下代码:

# 从Plotly直接复制的示例
import plotly.express as px
import pandas as pd

df = pd.DataFrame([
    dict(Task="Job A", Start='2009-01-01', Finish='2009-01-03'),
    dict(Task="Job B", Start='2009-01-03', Finish='2009-01-16'),
    dict(Task="Job C", Start='2009-01-16', Finish='2009-01-18')
])
# 添加颜色参数并从示例中删除y参数
fig = px.timeline(df, x_start="Start", x_end="Finish", color='Task')
fig.show()

如何创建时间线图

英文:

It should be pretty straight forward using plotly.express.timeline. Look at the first example on that page. If you want it on one y-axis position like your screenshot then try

# example directly from Plotly
import plotly.express as px
import pandas as pd

df = pd.DataFrame([
    dict(Task="Job A", Start='2009-01-01', Finish='2009-01-03'),
    dict(Task="Job B", Start='2009-01-03', Finish='2009-01-16'),
    dict(Task="Job C", Start='2009-01-16', Finish='2009-01-18')
])
# add color param and remove the y param from the example
fig = px.timeline(df, x_start="Start", x_end="Finish", color='Task')
fig.show()

如何创建时间线图

huangapple
  • 本文由 发表于 2023年5月31日 23:15:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/76375015.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定