我試圖purrr::map根據條件從迭代中產生稍微不同的結果。假設我有這段代碼生成圖并將它們存盤在資料框中:
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))
}))
假設我只想在第一個情節(或 Species ==“setosa”,無論如何)有這樣的傳說:
plots$plot[[1]]

那么隨后的情節將沒有這樣的傳說:
plots$plot[[2]]
guides(fill = "none")

反正有沒有直接在mutate/map呼叫中做到這一點?
uj5u.com熱心網友回復:
使用cur_group_id()來識別當前組。還有其他輔助函式,例如cur_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")
}))
uj5u.com熱心網友回復:
你可以添加一列showlegend到你的嵌套的資料,使用map2在兩個回圈data,并showlegend和你的繪圖功能中洗掉legend,如果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]]

轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/409146.html
標籤:
下一篇:對R中的非順序元素求和
