How to plot two charts with same X axis in R?

11,873

Solution 1

The basic idea is to melt the data set so that you have the values of the variables you want to plot on the y axis in a single column, with a second column distinguishing the source. For example:

data("economics")
dat.m <- melt(economics, measure.vars=c("pop", "unemploy"))

Then use facet_grid to plot each variable in a separate facet:

ggplot(dat.m, aes(x=date, y=value)) + geom_line() + facet_grid(variable~., scales="free_y")

Solution 2

Using the economics dataset that others mentioned a nice baseR solution might be.

layout(matrix(1:2, ncol = 1), widths = 1, heights = c(2,1.5), respect = FALSE)
par(mar = c(0, 4.1, 4.1, 2.1))
with(economics, plot(unemploy~date, type = 'l', xaxt = 'n', main = 'My Great Graph'))
par(mar = c(4.1, 4.1, 0, 2.1))
with(economics, plot(pop~date, type = 'l'))

my great graph

You'll note that you don't need to reshape the data at all since you're explicitly making two graphs rather than having to use a function where data is split on a factor. Also, those two graphs can be pretty much anything... like the second could be a histogram. Also, you'll note that in this code you could set the relative heights to whatever you want easily.

(this code executes much much faster than the ggplot2 solution... in case that matters... like live updating to a website or something, or you have lots of data, or need to make many of these graphs)

Solution 3

The yahoo finance charts are usually interactive, where you can move the time window and other features. To get a similar interactive effect I would recommend the googleVis package. The plots are made to a web browser so you can interact with them. Try:

install.packages("googleVis");library(googleVis);demo(googleVis)

the 8th graph to pop up is the one for timeseries. But this is not ggplot.

Share:
11,873
Admin
Author by

Admin

Updated on July 17, 2022

Comments