Erich Peterson Erich Peterson - 3 years ago 85
R Question

Adding Additional Y-Axis in R with ggplot2

Let's say I have the following (x0,y0) data that I have plotted (the y0-axis plotted on the left-hand side):


Further, I have another set of data (x1,y1) given as:

x1 y1

I am wanting to add an addition y1-axis on the right-hand side, which will have x1 as the break points and y1 as the labels. x1 and y0 are on the same scale, but the two datasets are of different lengths, and there is no formula which one can use to derive x1 from y0.


Answer Source

It's not entirely clear what you're looking for. Is it something like this?

df1 <- data_frame(x0 = c(500, 300),
              y0 = c(1, 3))

df2 <- data_frame(x1 = c(1.5, 3.2),
                  y1 = c(1, 2))

ggplot(df1, aes(x0, y0)) + geom_point() + 
  scale_y_continuous(expand = c(0.5,0.5),
                     sec.axis = sec_axis(trans = . ~ ., 
                                         breaks = df2$x1, labels = df2$y1))

enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download