有没有过滤的方法中 ggplot本身?也就是说,我想这样做
p <- ggplot(iris, aes(x = Sepal.Width, y = Sepal.Length, species)) +
geom_point(size = 4, shape = 4) +
geom_point(size = 1, shape = 5 # do this only for data that meets some condition. E.g. Species == "setosa")
Run Code Online (Sandbox Code Playgroud)
我知道我可以使用hacks,如设置size = 0,如果Species != "setosa"或重置数据,如下所示,但有所有hacks.
p <- ggplot(iris, aes(x = Sepal.Width, y = Sepal.Length, species)) +
geom_point(size = 4, shape = 4) +
geom_point(data = iris %>% filter(Species == "setosa"), colour = "red") +
geom_point(data = iris %>% filter(Species == "versicolor"), shape = 5)
Run Code Online (Sandbox Code Playgroud)
基本上,我有一个图表,只有在符合某个标准的情况下才能显示某些东西,而现在,我正在使用上面的黑客来完成这个并且它让我夜不能寐,我的灵魂慢慢地从混乱中消失我已经创造了.毋庸置疑,非常感谢任何帮助!
编辑
我担心我的例子可能过于简单化了.基本上,给定ggplot(data = ...),如何使用绑定到ggplot obj的数据添加这些图层:
Critera#1和#2可以是任何东西.例如,仅标记异常点.仅用红色绘制超出特定范围的点等.
我不想要
ggplot(data=subset(iris, Species=="setosa"),...)或ggplot(data=filter(iris,Species=="setosa").显然,图层现在接受一个函数作为数据参数,所以你可以使用它
pick <- function(condition){
function(d) d %>% filter_(condition)
}
ggplot(iris, aes(x = Sepal.Width, y = Sepal.Length, species)) +
geom_point(size = 4, shape = 4) +
geom_point(data = pick(~Species == "setosa"), colour = "red") +
geom_point(data = pick(~Species == "versicolor"), shape = 5)
Run Code Online (Sandbox Code Playgroud)
您可以使用公式符号通过匿名函数过滤数据~:
library(ggplot2)
library(dplyr)
ggplot(iris, aes(x = Sepal.Width, y = Sepal.Length, species)) +
geom_point(size = 4, shape = 4) +
geom_point(data = ~filter(.x, Species == "setosa"), colour = "red") +
geom_point(data = ~filter(.x, Species == "versicolor"), shape = 5)
Run Code Online (Sandbox Code Playgroud)

由reprex 包于 2021 年 11 月 15 日创建(v2.0.0)