在pandas中如何绘制时间线(起始时间和结束时间对)?

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

How to plot time line (start and end time pair) in pandas?

问题

You can use the following code to plot the start/end time pairs in pandas:

import pandas as pd
import matplotlib.pyplot as plt

data = [['set1', 0, 10], ['step2', 3, 12], ['step3', 8, 15]]
df = pd.DataFrame(data, columns=['name', 'start', 'end'])

plt.figure(figsize=(10, 2))
for index, row in df.iterrows():
    plt.barh(row['name'], width=row['end'] - row['start'], left=row['start'])

plt.xlabel('Time')
plt.ylabel('Step')
plt.title('Start/End Time Pairs')
plt.show()

这段代码可以用来绘制 pandas 中的起始/结束时间对,以显示每个步骤的起始时间和持续时间。

英文:

How to plot start/end time pair in pandas like the following?I need a plot to easily show which step from when, and how long it is.

data = [['set1', 0,10], ['step2', 3,12], ['step3', 8,15]]
df = pd.DataFrame(data, columns=['name', 'start','end'])

在pandas中如何绘制时间线(起始时间和结束时间对)?

答案1

得分: 1

水平堆叠条形图可以实现类似的效果:

ax = df.plot(kind='barh', stacked=True)
ax.set_xticks(range(0, df[['start','end']].sum(1).max() + 1, 1))

图片链接:在pandas中如何绘制时间线(起始时间和结束时间对)?

英文:

A quite similar effect can be achieved with horizontal bar (stacked) plot:

ax = df.plot(kind='barh', stacked=True)
ax.set_xticks(range(0, df[['start','end']].sum(1).max() + 1, 1))

在pandas中如何绘制时间线(起始时间和结束时间对)?

答案2

得分: 1

以下是翻译好的内容:

下面的代码提供了类似的功能。不确定是否正好符合您的要求。条形图具有均匀的颜色,而不是分段。

from matplotlib import patches
import numpy as np

#
# 示例数据
#

# 原始数据
data = [['set1', 0, 10], ['step2', 3, 12], ['step3', 8, 15]]
df = pd.DataFrame(data, columns=['name', 'start', 'end'])

# 具有更多步骤的数据
df = pd.DataFrame(
    {
        step: [start, start + duration]
        for step, start, duration in
        zip([f'step_{i}' for i in range(30)],
            0.5 * np.random.randn(30) + np.arange(0, 30),
            np.random.uniform(5, 10, (30,))
            )
    },
    index=['start', 'end']
).T.reset_index()
df.rename(columns={'index': 'name'}, inplace=True)

#
# 创建图表
#
height = 0.9

f, ax = plt.subplots(figsize=(10, 6))
for idx in range(len(df)):
    y0 = (idx + 1) - height / 2
    x0 = df.iloc[idx].start
    width = df.iloc[idx].end - x0
    ax.add_patch( patches.Rectangle((x0, y0), width, height) )
    ax.hlines(y0 + height / 2,
              xmin=df.start.min(),
              xmax=x0,
              color='k', linestyles=':', linewidth=0.5)
    
ax.axis((df.start.min(), df.end.max(), 1 - height, len(df) + height))
ax.set_xlabel('时间')
ax.set_ylabel('名称')
ax.set_yticks(range(1, len(df) + 1))
ax.set_yticklabels(df.name)
plt.show()

在pandas中如何绘制时间线(起始时间和结束时间对)?

英文:

The code below provides similar functionality. Not sure if it's exactly what you were after. Bars have a uniform colour rather than being segmented.

在pandas中如何绘制时间线(起始时间和结束时间对)?

from matplotlib import patches
import numpy as np

#
# Example data
#

#Original data
data = [['set1', 0, 10], ['step2', 3, 12], ['step3', 8, 15]]
df = pd.DataFrame(data, columns=['name', 'start', 'end'])

#Data with more steps
df = pd.DataFrame(
    {
        step: [start, start + duration]
        for step, start, duration in
        zip([f'step_{i}' for i in range(30)],
            0.5 * np.random.randn(30) + np.arange(0, 30),
            np.random.uniform(5, 10, (30,))
            )
    },
    index=['start', 'end']
).T.reset_index()
df.rename(columns={'index': 'name'}, inplace=True)

#
# Create plot
#
height = 0.9

f, ax = plt.subplots(figsize=(10, 6))
for idx in range(len(df)):
    y0 = (idx + 1) - height / 2
    x0 = df.iloc[idx].start
    width = df.iloc[idx].end - x0
    ax.add_patch( patches.Rectangle((x0, y0), width, height) )
    ax.hlines(y0 + height / 2,
              xmin=df.start.min(),
              xmax=x0,
              color='k', linestyles=':', linewidth=0.5)
    
ax.axis((df.start.min(), df.end.max(), 1 - height, len(df) + height))
ax.set_xlabel('time')
ax.set_ylabel('name')
ax.set_yticks(range(1, len(df) + 1))
ax.set_yticklabels(df.name)
plt.show()

huangapple
  • 本文由 发表于 2023年8月4日 21:16:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/76836290.html
匿名

发表评论

匿名网友

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

确定