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
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, ...)
Create a Title for a Plot With Pyplot, you can use the title() function to set a title for the plot.
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.
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 .
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)
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With