I am trying to produce a slightly different result from a purrr::map iteration depending on a condition. Say I have this code producing plots and storing them in a dataframe:
library(tidyverse)
#> -- Attaching packages --------------------------------------- tidyverse 1.3.1 --
#> v ggplot2 3.3.5 v purrr 0.3.4
#> v tibble 3.1.6 v dplyr 1.0.7
#> v tidyr 1.1.4 v stringr 1.4.0
#> v readr 2.1.0 v forcats 0.5.1
#> -- Conflicts ------------------------------------------ tidyverse_conflicts() --
#> x dplyr::filter() masks stats::filter()
#> x dplyr::lag() masks stats::lag()
plots <- iris |>
group_by(Species) |>
nest() |>
mutate(plot = map(data, ~ {
ggplot(.x)
geom_point(aes(x = Sepal.Length, y = Sepal.Width, fill = Petal.Width))
}))
Say I only wanted to the first plot (or Species == "setosa", whatever) to have a legend like so:
plots$plot[[1]]

Then subsequent plots would have no legend like so:
plots$plot[[2]]
guides(fill = "none")

Is there anyway to do that directly in the mutate/map call?
CodePudding user response:
Use cur_group_id() to identify the current group. There are also other helper functions like cur_group(), which could give you even finer control over the operations to be done within each group.
library(dplyr)
library(tidyr)
library(ggplot2)
library(purrr)
plots <- iris |>
group_by(Species) |>
nest() |>
mutate(plot = map(data, ~ {
ggplot(.x)
geom_point(aes(x = Sepal.Length, y = Sepal.Width, fill = Petal.Width))
if (cur_group_id() > 1L) guides(fill = "none")
}))
CodePudding user response:
You could add a column showlegend to your nested data, use map2 to loop over both data and showlegend and inside your plotting function remove the legend if showlegend == FALSE:
library(ggplot2)
library(purrr)
library(dplyr)
library(tidyr)
plots <- iris |>
group_by(Species) |>
nest() |>
mutate(
showlegend = Species == "setosa",
plot = map2(data, showlegend, ~ {
guide <- if (!showlegend) guides(fill = "none")
ggplot(.x)
geom_point(aes(x = Sepal.Length, y = Sepal.Width, fill = Petal.Width))
guide
})
)
plots$plot[[1]]

plots$plot[[2]]

