I want to have two graphs in one. They are both time series, but different scales (let's say heights and weights). The way I want to present this is by having two figures on top of each other that would share the x-label, but have different y-labels.
I have two different problems:
- If I do 2x1 facets, the default position for facet labels is on the right with vertical text, I would rather have them on top of the graphs as (sub)-titles
ylab()
defines one ylabel for all facets, but I have two different variables/scales. Is it possible to "split" it and have two different ylabel (say "grams" for weight and "inches" for height)?
Thanks!
EDIT:
Ok, this is the code. mn is the variable that is ploted against time, grouped by risk. But the meaning of mn
depends on var
. For some values of var
it is weight
, for others it is height
.
qplot(time, mn, data=d.plot.long,
color=risk, group=risk,
geom=c("line","point"),
position=position_dodge(.2))+
geom_point(size=5, position=position_dodge(.2))+
geom_errorbar(aes(x=time, y=mn, ymin=low, ymax=hi),width=.3 ,position=position_dodge(.2))+
facet_grid(var~.,scales='free_y')+
xlab('Time')+ylab('')+
scale_color_discrete(name="The grouping variable", breaks=c("Hi","Low"), labels=(c("Group A","Group B")))
Use
gtable:::rbind_gtable
; other answers won't properly align the axes.As others have said, reproducibility makes questions easier to answer. However, this is the sort of question that can be easily answered with a general case.
ggplot2 offers somewhat limited options for multiple graphs on a single plate. The R Cookbook offers a pretty good and very easy to use workaround here. I can quickly walk you through it for your case:
First, some two simple sets of time series in a dataframe:
Next, create your graphs. Since you want them to share an x axis, we'll remove it from the top graph:
Next, run the code from the cookbook to set up the multiplot function:
...and use the new function to lay out your graphs, one on top of the other.
(I'd like to show you the final output, but it seems I've not got enough reputation to post an image! Try running all that to see the result for yourself.)
Is that what you're looking for?
Using the data of @Joe, it's probably easier to use the
gridExtra
package.The code:
The result: