r - 根据 ggplot 中其他列中的值在 ggplot 中包含垂直线

标签 r ggplot2 plot tidyverse data-visualization

这是一个令人困惑的标题,但我拥有的是一个 df (更大,但是),如下所示:

df
# A tibble: 10 × 3
    week count protest
   <int> <dbl>   <dbl>
 1     1  259.       0
 2     2  509.       0
 3     3  556.       0
 4     4  588.       0
 5     5  541.       0
 6     6  576.       1
 7     7  531.       0
 8     8  518.       0
 9     9  470.       1
10    10  392.       1

我想要的是在 x 轴上绘制 countweek 的线。但我还想为每个 week 添加一条垂直线,其中包含 protest == 1 的值。

我做了这样的事情:

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

enter image description here

但正如你所看到的,我只得到了第一个具有 protest == 1 的观察结果,而不是所有具有 protest == 1 的观察结果,正如我想要的那样。有任何想法吗? 谢谢!

最佳答案

要为抗议次数等于 1 的任何一周添加红线,您可以使用以下代码

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

example1

关于r - 根据 ggplot 中其他列中的值在 ggplot 中包含垂直线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70184239/

相关文章:

python - 调整条形图上的颜色编码,以便所有值在 matplotlib 中都正确编码

R:标题用par()减半

r - csv 文件,或制表符分隔文件,或任何文件

r - geom_raster 和 geom_point 的两种颜色渐变

r - 通过雪在并行代码中使用 Rcpp 来创建集群

r - 从 bayesplot R 包更改 mcmc_areas() 图中的 y 轴文本

r - ggplot错误: ssh X11 forwarding

python - 使用 matplotlib 绘制直方图或散点图

c++ - 检查 R 函数是否依赖于 C/C++ 编译代码的函数?

r - 如何将多个 ggplot2 元素组合到函数的返回中?