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