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

R语言绘制因子类时间序列列表 实现多组事件时长对比

解决方案

你需要的是基于分类Y轴的区间线段图,两种实现方案如下:

方案1:基础R绘图(无需转数据框,直接使用现有向量)

直接在你已有的plot代码基础上扩展,手动给每个午餐选项分配Y轴位置即可:

# 给每个餐品分配Y轴坐标位置
y_pos <- c(grilledcheese = 1, pasta = 2, soup = 3)
# 自定义Y轴标签
y_labels <- c("grilled cheese", "pasta", "soup")

# 初始化画布,先绘制grilledcheese的线段
plot(x = grilledcheese, y = rep(y_pos["grilledcheese"], length(grilledcheese)),
     type = "l", lwd = 4, # type="l"指定为线图,lwd调整线粗
     xlim = c(0, 20), ylim = c(0.5, 3.5), # 设定坐标轴范围避免内容裁切
     xlab = "天数", ylab = "午餐选项",
     yaxt = "n") # 关闭默认Y轴,后续手动自定义

# 手动添加Y轴
axis(side = 2, at = y_pos, labels = y_labels, las = 1)

# 追加pasta的线段
lines(x = pasta, y = rep(y_pos["pasta"], length(pasta)), lwd = 4, col = "red")

# 追加soup的线段
lines(x = soup, y = rep(y_pos["soup"], length(soup)), lwd = 4, col = "blue")

如果需要散点样式的展示,把type = "l"去掉,lines函数换成points函数即可。

方案2:ggplot绘图(效果更美观,维护性更强)

虽然ggplot需要传入数据框,但转换成本极低,几行代码即可完成,后续修改样式也更方便:

library(ggplot2)

# 快速拼接数据框
food_data <- data.frame(
  day = c(grilledcheese, pasta, soup),
  food = rep(c("grilled cheese", "pasta", "soup"), 
             times = c(length(grilledcheese), length(pasta), length(soup)))
)

# 绘制线段图
ggplot(food_data, aes(x = day, y = food)) +
  geom_line(linewidth = 4) + # 调整线段粗细
  labs(x = "天数", y = "午餐选项") +
  theme_bw()

如果不需要展示每日的点,只想展示起止区间,可以直接计算每个餐品的最小/最大天数绘制色块,代码更简洁:

library(ggplot2)

# 仅统计每个餐品的起止日期
food_range <- data.frame(
  food = c("grilled cheese", "pasta", "soup"),
  start = c(min(grilledcheese), min(pasta), min(soup)),
  end = c(max(grilledcheese), max(pasta), max(soup))
)

# 绘制区间色块图
ggplot(food_range, aes(y = food)) +
  geom_rect(aes(xmin = start, xmax = end, 
                ymin = as.numeric(factor(food)) - 0.2, 
                ymax = as.numeric(factor(food)) + 0.2),
            fill = "#2c7fb8", alpha = 0.8) +
  labs(x = "天数", y = "午餐选项") +
  theme_minimal()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 01:39:01