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

R语言ggplot中如何根据另一列取值添加多条对应垂直参考线

问题根源

match(1, protest)函数仅返回第一个满足protest1的观测位置,因此你只能拿到单个week值,最终只生成一条垂直线。
geom_vline的xintercept参数支持接收多值向量,每一个值都会对应生成一条垂直线,只要把所有protest
1对应的week值传入即可实现需求。

可用实现代码

写法1:直接提取符合条件的向量(简单直观)

library(ggplot2)
ggplot(berlin_week, aes(x=week, y=count)) +
  geom_line() +
  geom_vline(xintercept = berlin_week$week[berlin_week$protest == 1], col = "red")

写法2:传入数据子集(适配tidyverse管道流、动态数据场景)

library(ggplot2)
ggplot(berlin_week, aes(x=week, y=count)) +
  geom_line() +
  geom_vline(data = ~subset(.x, protest == 1), aes(xintercept = week), col = "red")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 05:06:03