multiple graphs in one canvas using ggplot2
Solution 1:
You can use grid.arrange()
in the gridExtra package like this:
grid.arrange(p1, p2)
Solution 2:
Julio,
You mention that p1 and p2 have the same x-axis, but the reordering you do based on mean does not make them the same. p1
's axis goes "one --> two --> three" while p2
's axis goes "two --> one --> three". Is this intentional?
Regardless, ggplot
offers a few other solutions to combine these plots into one, namely colour
and faceting
(which you may have already tried?). The first step to either of these is to melt
your data.frame to long format. We will identify the id variable "Type" and melt
assumes the rest of the columns are to be melted
.
test.m <- melt(test, id.var = "Type")
A quick check of the structure of the new object indicates most everything is in line, except the levels for type are a bit out of whack:
> str(test.m)
'data.frame': 12 obs. of 3 variables:
$ Type : Factor w/ 3 levels "One","Three",..: 1 3 1 1 2 2 1 3 1 1 ...
$ variable: Factor w/ 2 levels "RatingA","RatingB": 1 1 1 1 1 1 2 2 2 2 ...
$ value : int 3 5 5 7 4 8 36 53 57 74 ...
So let's rearrage the levels:
test.m$Type <- factor(test.m$Type, c("One", "Three", "Two"), c("One", "Two", "Three"))
Now for the plotting. With colour:
ggplot(test.m, aes(x = Type, y = value, group = variable, colour = variable)) +
stat_summary(fun.y = "mean", geom = "point")
or with facets:
ggplot(test.m, aes(x = Type, y = value, group = variable)) +
stat_summary(fun.y = "mean", geom = "point") +
facet_grid(variable ~ ., scales = "free")
Note I used the scales = "free"
argument in the faceting so that each plot has its' own scale. Simply remove that argument if that's not the effect you want.