如何制作条件ggplot几何

时间:2019-04-08 16:41:54

标签: r if-statement ggplot2

library(tidyverse)

df1 <- data.frame(Name = c("Jack", "Jill", "John"),
                  Qty =  c(3, 8, 4), 
                  Violation = c("F", "T", "F"))

ggplot(df1, aes(Name, Qty, group = 1)) + 
  geom_line() +
  geom_point() + 
  geom_hline(aes(yintercept = 5), linetype = "dashed") + 
  geom_point(data = df1 %>% filter(Violation == "T"), color = "red")

ggplot conditional highlight

上面的代码突出显示了符合Violation == "T"标准的所有数据点。但是,我的数据帧发生了变化,有时不包含任何符合Violation == "T"的数据点。发生这种情况时,我会收到如下错误:

df2 <- data.frame(Name = c("Jack", "Jill", "John"),
                  Qty =  c(3, 2, 4), 
                  Violation = c("F", "F", "F"))

ggplot(df2, aes(Name, Qty, group = 1)) + 
  geom_line() +
  geom_point() + 
  geom_hline(aes(yintercept = 5), linetype = "dashed") + 
  geom_point(data = df2 %>% filter(Violation == "T"), color = "red")

#> Error: Aesthetics must be either length 1 or the same as the data (1): x, y

我是否需要构造某种类型的ifelse()语句以使我的ggplot代码正常工作,无论是否有Violation == "T"

1 个答案:

答案 0 :(得分:2)

您可以直接按因子水平直接为点着色。通过将“ F”变黑和“ T”变红,您可以获得相同的效果。

ggplot(df2, aes(Name, Qty, group=1)) + 
     geom_line() +
     geom_point(aes(col=Violation)) + 
     geom_hline(aes(yintercept = 5), linetype = "dashed")+
     scale_color_manual(values=c('black','red'))