TLol
TLol

Reputation: 53

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

How do I plot 2 charts using the same x axis in R with ggplot2?

I am looking for something like: https://i.sstatic.net/B9QT7.png

Upvotes: 3

Views: 14209

Answers (4)

John
John

Reputation: 23768

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)

Upvotes: 9

joran
joran

Reputation: 173737

The strategy outline by Ista using ggplot2 can be achieved using the lattice package as well. Using the same data:

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

Then we use xyplot, specifying two rows and one column via layout and forcing separate y axis scales using the scales argument:

xyplot(value~date|variable,data = dat.m, 
    panel = "panel.lines", layout = c(1,2),
    scales = list(y = list(relation = "free")))

enter image description here

Upvotes: 0

Seth
Seth

Reputation: 4795

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.

Upvotes: 1

Ista
Ista

Reputation: 10437

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")

Upvotes: 2

Related Questions