tom sawyer
tom sawyer

Reputation: 57

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 e.g., 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.

Upvotes: 0

Views: 1671

Answers (1)

Jake
Jake

Reputation: 520

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)

Upvotes: 1

Related Questions