You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于事件计数DataFrame绘制累计密度折线图?

生成累计事件数折线图解决方案

问题说明

现有如下DataFrame:

df = 
   Time_to_event  event
0         0 days    443
1         1 days    226
2         2 days    162
3         3 days     72
4         4 days     55
5         5 days     30
6         6 days     36
7         7 days     18
8         8 days     15
9         9 days     14
10       10 days     21
11       11 days     13
12       12 days     10
13       13 days     10
14       14 days      8

需要生成每日事件数累加的累计图(第0天为443,第1天为443+226,以此类推)。之前使用seaborn.histplot生成的柱状图效果不佳,希望替换为折线图。

解决方法

1. 数据预处理

首先将Time_to_event转换为数值型天数,并计算事件数的累计和:

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

# 提取天数数值
df['days'] = df['Time_to_event'].str.extract('(\d+)').astype(int)
# 计算累计事件数
df['cumulative_event'] = df['event'].cumsum()

2. 绘制累计折线图

使用seaborn.lineplot直接绘制折线,这是最适合此类需求的方式:

# 绘制累计事件数折线,marker参数可选,用于标记每个数据点
sns.lineplot(data=df, x='days', y='cumulative_event', marker='o')

# 添加图表标注(可选)
plt.title('累计事件数随天数变化')
plt.xlabel('天数')
plt.ylabel('累计事件数')
plt.grid(True, alpha=0.3)  # 添加网格线提升可读性
plt.show()

3. 可选:绘制累计比例折线图

如果需要展示累计事件数占总事件数的比例,可按以下方式处理:

total_events = df['event'].sum()
df['cumulative_proportion'] = df['cumulative_event'] / total_events

# 绘制累计比例折线
sns.lineplot(data=df, x='days', y='cumulative_proportion', marker='s')

plt.title('累计事件比例随天数变化')
plt.xlabel('天数')
plt.ylabel('累计比例')
plt.ylim(0, 1)  # 限制y轴范围在0-1之间
plt.grid(True, alpha=0.3)
plt.show()

内容的提问来源于stack exchange,提问作者Economist_Ayahuasca

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 02:35:21