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

基于含连续与分类变量的dataframe绘制指定分类累计计数图

数据预处理

首先筛选目标分类、排序并计算累计计数:

# 筛选Category为A的观测
df_a <- subset(df, Category == "A")
# 按Continuous列升序排列
df_a_sorted <- df_a[order(df_a$Continuous), ]
# 生成累计计数列
df_a_sorted$cum_count <- seq(nrow(df_a_sorted))
# 补充x=0、y=0的起始点,符合从0开始统计的需求
df_plot <- rbind(
  data.frame(Continuous = 0, cum_count = 0),
  df_a_sorted[, c("Continuous", "cum_count")]
)

基础R绘图实现

plot(
  x = df_plot$Continuous,
  y = df_plot$cum_count,
  type = "s", # *阶梯线类型,适配累计计数的突变特征*
  xlab = "连续变量取值",
  ylab = "A类累计观测数量",
  main = "A类观测累计增长趋势",
  lwd = 2,
  col = "#2c7fb8"
)
# 可选:添加实际观测点标记
points(df_a_sorted$Continuous, df_a_sorted$cum_count, pch = 16, col = "#d95f0e", cex = 1.2)

ggplot2实现

library(ggplot2)

ggplot(df_plot, aes(x = Continuous, y = cum_count)) +
  geom_step(linewidth = 1.2, color = "#2c7fb8") +
  geom_point(data = df_a_sorted, color = "#d95f0e", size = 2.5) +
  labs(
    x = "连续变量取值",
    y = "A类累计观测数量",
    title = "A类观测随连续变量增大的累计增长趋势"
  ) +
  theme_bw(base_size = 12)

用示例数据运行后,会得到符合要求的趋势图:x=10时累计数为2,x=12时为3,x=14时为4,x=20时为5,完全匹配统计规则。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 16:30:03