简体   繁体   中英

Adding titles and formatting Y-axis labels for multiple plots produced by ggplot2

I have a multiplot with 10 scatter plots produced using ggplot2. The code i have used to create the plot has been lifted from here R cookbook. My problem is that i want to add different titles for each and every scatter plot eg, plot 1 title can be titled "plot 1", while plot 2 can be titled "plot 2" and so on and so forth. I would also want to change the labels from the current label "Y" to "purchases" for all the plots.

Just create your plots and title each one individually as the code you referenced does. Then arrange using the gridExtra package. ggtitle does the title, the ylab function can be used for the y-label.

library(ggplot2)

# This example uses the ChickWeight dataset, which comes with ggplot2
# First plot
p1 <- ggplot(ChickWeight, aes(x=Time, y=weight, colour=Diet, group=Chick)) +
    geom_line() +
    ggtitle("Growth curve for individual chicks")

# Second plot
p2 <- ggplot(ChickWeight, aes(x=Time, y=weight, colour=Diet)) +
    geom_point(alpha=.3) +
    geom_smooth(alpha=.2, size=1) +
    ggtitle("Fitted growth curve per diet")

 # Third plot
p3 <- ggplot(subset(ChickWeight, Time==21), aes(x=weight, colour=Diet)) +
    geom_density() +
    ggtitle("Final weight, by diet")

# Fourth plot
p4 <- ggplot(subset(ChickWeight, Time==21), aes(x=weight, fill=Diet)) +
    geom_histogram(colour="black", binwidth=50) +
    facet_grid(Diet ~ .) +
    ggtitle("Final weight, by diet") +
    theme(legend.position="none")        # No legend (redundant in this graph)    

require(gridExtra)
grid.arrange(p1, p2, p3, p4, nrow = 2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM