0
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 条件高亮

上面的代码突出显示了任何符合条件的数据点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"没有?

4

1 回答 1

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'))
于 2019-04-08T16:48:20.603 回答