Ggplot: display layers only if certain criteria are met

Is there a way to filter inside ggplot? That is, let's say I want to do this

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") 

I know that there are hacks that I can use, for example, set the size = 0 if Species != "setosa"or reset the data, as shown below, but everything is hacked there.

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)

Basically, I have a chart where certain things should be displayed only if certain criteria are met, and right now I use the hack above to accomplish this, and this holds me back at night, my soul is slowly dying from the mess that I created. Needless to say, any help would be greatly appreciated!

Edit

, , , . , ggplot(data = ...), , , , ggplot obj:

  • , # 1. . , , ( , , , , 0)
  • , # 2.

Critera # 1 # 2 . . . , ..

  • ala ggplot(data=subset(iris, Species=="setosa"),...) ggplot(data=filter(iris,Species=="setosa").
  • (, scale = manual , , NULL/NA ..). , 1000 1 , , , , 1000 .
+1
1

,

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)
+4

Source: https://habr.com/ru/post/1693610/


All Articles