1

I've got data for prices and volumes of a good and I'd like to include information for both in a single plot. I've got it working so that it shows both, but volume happens to be much larger than prices for my data, so I need different scales for them.

Here's some example code that's representative of what I'm working with:

days = c(1:100)
price = rnorm(100,mean=2,sd=.2)
volume = rbinom(100, size=1000, prob=.2)
df = data.frame(days,price,volume)

Now, if I use

ggplot() + geom_bar(data=df, aes(x=days,y=volume), stat="identity") + geom_point(data=df, aes(x=days,y=price)) 

It almost does what I want (i.e. one single chart that has both) but since it has the same scale for both price and volume, you can't really tell the variation in prices. Prices go from about 1.5-2.5 while most volume is in the range of ~200.

So what I want is for prices to be scaled at something like 0-3 and volume to be scaled at something like 0-1000 so you see a scatter plot of the prices with a little bar chart below it that gives information about the volume on each day. I'm pretty sure that this should be a straightforward thing to do, but after two hours of Google and reading manuals, I ask you fine people.

  • Yeah, `ggplot` doesn't really let you do dual y-axes. It's pretty strict about one variable per aesthetic, by design. – Marius Sep 10 '13 at 21:39
  • 1
    `ggplot2` very intentionally doesn't allow double y-axes - you can see the author's (hadley's) explanation at the question linked in my above comment. – Matt Parker Sep 10 '13 at 21:41
  • Splitting your plot into two facets (using `facet_wrap`) might be a good alternative - it gets you both series plotted in a relatively compact form with sensible axis scaling. – Matt Parker Sep 10 '13 at 21:43
  • Ah, that's a bit frustrating. I'll try to backdoor it with facet_wrap, thanks. – Johnathan Maddon Sep 10 '13 at 21:47
  • 1
    And, unrelated to your question - I usually find it easier to write multilayer ggplots like this: `ggplot(df, aes(x = days)) + geom_line(aes(y = volume)) + geom_line(aes(y = price))` - saves on the typing. All of the layers you add will inherit the aesthetic mappings from the initial `ggplot()`, so if you know you're going to use `x = days` throughout, it's easier to put it up there. – Matt Parker Sep 10 '13 at 21:47
  • Perhaps this post can help: http://rpubs.com/kohske/dual_axis_in_ggplot2 – user20650 Sep 11 '13 at 05:26
  • @user20650 that totally worked, thanks! – Johnathan Maddon Sep 11 '13 at 19:09

0 Answers0