0

I have been googling for some time and there is no easy way to do dual axis using ggplot? Seems odd because its a powerful package but cant do dual axis?

My problem is basic. I'd like to plot both data sets on same plot with 2 axis.

d1 = data.frame(x = rnorm(15),y = rnorm(15))
d2 = data.frame(x = rnorm(15),y = rnorm(15))
ggplot(data = d1, aes(x= x,y =y))+geom_line()
ggplot(data = d2, aes(x= x,y =y))+geom_line()

I do not want to use facet_wrap or facet_grid or align charts underneath one another.

Thoughts? Help from ggplot people?

Thank you.

user3022875
  • 8,598
  • 26
  • 103
  • 167
  • 2
    You can plot both on the same plot in different layers, but not with two y-axes (at least not without some serious hacking). That's deliberate: Hadley thinks dual and split y-axes are usually misleading. – alistaire Jul 23 '16 at 00:11
  • It's not `ggplot`, but `plotly` does allow split y-axis plots. – Matt Sandgren Jul 23 '16 at 00:24
  • [reproduce-the-economist-chart-with-dual-axis](http://stackoverflow.com/questions/37347115/reproduce-a-the-economist-chart-with-dual-axis/37369764#37369764); [adding-secondary-y-axis-on-top-of-a-plot](http://stackoverflow.com/questions/36754891/ggplot2-adding-secondary-y-axis-on-top-of-a-plot/36759348#36759348); [how-to-put-a-transformed-scale-on-the-right-side-of-a-ggplot2](http://stackoverflow.com/questions/18989001/how-can-i-put-a-transformed-scale-on-the-right-side-of-a-ggplot2/19082285#19082285); [cowplot's switch_axis.R](https://github.com/wilkelab/cowplot/blob/master/R/switch_axis.R) – Sandy Muspratt Jul 23 '16 at 02:59
  • I think that [this](http://stackoverflow.com/questions/26917689/how-to-use-facets-with-a-dual-y-axis-ggplot/40746716#40746716) could help you. – Kryštof Chytrý Jan 19 '17 at 19:49

1 Answers1

1

I added a function to a Github package, plotflow, I maintain that can do this. If you don't want to install the package just use the source code.

devtools::install_github('trinker/plotflow')
library(plotflow)

d1 = data.frame(x = rnorm(15),y = rnorm(15))
d2 = data.frame(x = rnorm(15),y = rnorm(15))

plotflow::ggdual_axis(
    ggplot(data = d1, aes(x= x,y =y))+geom_line(),
    ggplot(data = d2, aes(x= x,y =y))+geom_line()
)

enter image description here

Tyler Rinker
  • 108,132
  • 65
  • 322
  • 519