Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add titles to ggplots created with map()

Tags:

r

ggplot2

purrr

What's the easiest way to add titles to each ggplot that I've created below using the map function? I want the titles to reflect the name of each data frame - i.e. 4, 6, 8 (cylinders).

Thanks :)

mtcars_split <- 
  mtcars %>%
  split(mtcars$cyl)

plots <-
  mtcars_split %>%
  map(~ ggplot(data=.,mapping = aes(y=mpg,x=wt)) + 
        geom_jitter() 
  # + ggtitle(....))

plots
like image 711
jimbo Avatar asked Jan 27 '18 02:01

jimbo


People also ask

How do I add a title to a map in R?

Use the title() function title() can be also used to add titles to a graph. A simplified format is : title(main = NULL, sub = NULL, xlab = NULL, ylab = NULL, ...)

Which function lets you set the title of the plot?

Create a Title for a Plot With Pyplot, you can use the title() function to set a title for the plot.

How do you add a title to a Ggplot object?

Adding a title To add a title to your plot, add the code +ggtitle("Your Title Here") to your line of basic ggplot code. Ensure you have quotation marks at the start and end of your title. If you have a particulary long title that would work better on two lines, use \n for a new line. Make sure to use the correct slash.

How do I add a title to a histogram in R?

You can change the title of the histogram by adding main as an argument to hist() function. In this case, you make a histogram of the AirPassengers data set with the title “Histogram for Air Passengers”: If you want to adjust the label of the x-axis, add xlab .


1 Answers

Use map2 with names.

plots <- map2(
  mtcars_split,
  names(mtcars_split),
  ~ggplot(data = .x, mapping = aes(y = mpg, x = wt)) + 
    geom_jitter() +
    ggtitle(.y)
)

Edit: alistaire pointed out this is the same as imap

plots <- imap(
  mtcars_split,
  ~ggplot(data = .x, mapping = aes(y = mpg, x = wt)) + 
    geom_jitter() +
    ggtitle(.y)
)
like image 70
Paul Avatar answered Sep 28 '22 23:09

Paul