Adding grouped variable name to plot with group_nest and map

左心房为你撑大大i 提交于 2020-01-16 09:40:11

问题


This is likely a syntax question. Here's the problem recreated with some dummy data.

I'm working with a larger dataset, and I want to perform a group_nest and then create some plots with the title of the group. All goes well, until the title is just repeated.

library(tidyverse)

N <- 30
df <- tibble(type = rep(c("small","medium","high"), each=N/3),
             dummy = rep(c(1,5,10),each=10),
             xvals = rep(1:10,3),
             A = rnorm(N)*dummy,
             B = rnorm(N)*dummy,
             C = rnorm(N)*dummy) %>%
  mutate(type = factor(type, levels=c("small","medium","high"))) %>%
  pivot_longer(cols=-c(type,xvals), names_to="metric", values_to = "value") %>%
  group_by(type) %>%
  group_nest(.key="data") %>%
  mutate(gplot = map(data, ~ggplot(data=.x, aes(x=xvals,y=value))+
                       geom_point() +
                       facet_grid(rows=vars(metric)) +
                       ggtitle(paste0(type) ## THIS IS WHERE THE PROBLEM IS ##
                      )))

#view the plots
df$gplot[[1]] #has title "small"
df$gplot[[2]] #has title "small", should be "medium"
df$gplot[[3]] #has title "small", should be "large"

Here's what I get:

This is what I want:


回答1:


Maybe try map2 instead?

df <- tibble(type = rep(c("small","medium","high"), each=N/3),
                         dummy = rep(c(1,5,10),each=10),
                         xvals = rep(1:10,3),
                         A = rnorm(N)*dummy,
                         B = rnorm(N)*dummy,
                         C = rnorm(N)*dummy) %>%
    mutate(type = factor(type, levels=c("small","medium","high"))) %>%
    pivot_longer(cols=-c(type,xvals), names_to="metric", values_to = "value") %>%
    group_by(type) %>%
    group_nest(.key="data") %>%
    mutate(gplot = map2(data,type, ~ggplot(data=.x, aes(x=xvals,y=value))+
                                            geom_point() +
                                            facet_grid(rows=vars(metric)) +
                                            ggtitle(.y ## THIS IS WHERE THE PROBLEM IS ##
                                            )))


来源:https://stackoverflow.com/questions/58383438/adding-grouped-variable-name-to-plot-with-group-nest-and-map

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!