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")
我知道我可以使用一些技巧,例如设置 size = 0 if
Species != "setosa"
或重置数据,如下所示,但有所有黑客。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)
基本上,我有一个图表,其中只有在满足特定条件时才应该显示某些东西,而现在,我正在使用上面的黑客来完成这个,它让我彻夜难眠,我的灵魂慢慢地死于我的困惑已创建。不用说,任何帮助将不胜感激!
编辑
恐怕我的例子可能过于简单化了。基本上,给定
ggplot(data = ...)
,我如何添加这些图层,全部使用绑定(bind)到 ggplot obj 的数据:标准#1 和#2 可以是任何东西。例如。仅标注异常点。仅用红色绘制特定范围之外的点等。
我 不要想要
ggplot(data=subset(iris, Species=="setosa"),...)
或 ggplot(data=filter(iris,Species=="setosa")
. 最佳答案
您可以使用 ~
使用匿名函数过滤数据。公式符号:
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)
由 reprex package 创建于 2021-11-15| (v2.0.0)
关于r - ggplot : plotting layers only if certain criteria are met,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35806310/