首页 文章

ggplot:仅在满足某些条件时绘制图层

提问于
浏览
2

是否有一种在 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")

我知道我可以使用hacks,如设置size = 0,如果 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)

基本上,我有一个图表,只有在符合某个标准的情况下才能显示某些事物,而现在,我正在使用上面的黑客来完成这个并且它让我夜不能寐,我的灵魂慢慢地从混乱中消失我已经创造了 . 不用说,任何帮助都将非常感谢!

Edit

我担心我的例子可能过于简单化了 . 基本上,给定 ggplot(data = ...) ,如何添加这些图层, all using the data bound to the ggplot obj

  • 绘制曲线

  • 在符合条件#1的点上绘制点 . 这些点是红色的 . 没有得到一个点的点(不是像点大小设置为零,或者alpha设置为0的黑客)

  • 为符合条件#2的点添加标签 .

Critera#1和#2可以是任何东西 . 例如 . 仅标记异常点 . 仅用红色绘制超出特定范围的那些点,等等 .

don't

  • 绑定新数据集ala ggplot(data=subset(iris, Species=="setosa"),...)ggplot(data=filter(iris,Species=="setosa") .

  • 使用缩放黑客(比如设置比例=手动和任何不是't meet the criteria gets a NULL/NA, etc). For example, if I had 1000 points and only 1 point met a given criteria, I want it to only apply it'的绘图逻辑到那一点而不是看,并设置所有1000点的样式

1 回答

  • 6

    显然,图层现在接受一个函数作为数据参数,所以你可以使用它

    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)
    

相关问题