Making a data frame column of ggplot
objects is a little unusual and cumbersome, but it can work if that's what suits the situation. (It seemed like geom_bar
didn't actually make sense for this data, so I switched to histograms on a filtered subset of carbs).
With your method, you create the column of plots, save the data frame into a variable, then map2
across the list-column of plots and the vector of carb
s, adding a title to each plot. Then you can print any item from the resulting list, or print them all with map
or walk
.
library(tidyverse)
df <- mtcars %>%
filter(carb %in% c(1, 2, 4)) %>%
mutate(carb = as.character(carb))
df_with_plots <- df %>%
group_by(carb) %>%
nest() %>%
mutate(plot = map(data, function(.x) {
.x %>%
ggplot() +
geom_histogram(aes(mpg))
}))
plots1 <- map2(df_with_plots$plot, df_with_plots$carb, ~(.x + labs(title = .y)))
# plots1[[1]] # would print out first plot in the list
walk(plots1, print)
Removed additional plots for the sake of brevity
The other option, which seems more straightforward, is to split the data frame into a list of data frames, then create plots however you need for each of those.
A few advantages: calling split
gives each value of carb
as the name of the corresponding list item, which you can access easily with imap
, and which carries over to the plots2
list (see below how I printed a plot by name). You can also do this in a single step. I also have a hard time working with nested data, because I'd prefer to be able to see the data frames, which you can do by printing out the split list of data frames.
plots2 <- df %>%
split(.$carb) %>%
imap(function(carb_df, carb) {
ggplot(carb_df) +
geom_histogram(aes(mpg)) +
labs(title = carb)
})
plots2[["4"]]
As with the first method, you can print out all the plots with walk(plots2, print)
.
n
? IN the current setup, it would beimap
andggtitle
pass.y
ggplot
objects in your data frame, it might be more straightforward to split the data by carb, then map over that list of data frames to make plots. Such as here: stackoverflow.com/q/45107404/5325862