0

I have two plots with different x-axis but same y-axis. The order of each x-axis has to be stay in that way. I want to converge two graphs into one, by having one x-axis on bottom and one on top.

plot1 plot2

plot1 <- ggplot(df1, aes(x = Target1, y = RT1)) + geom_point() + geom_line(aes(group = 1)) 
plot2 <- ggplot(df2, aes(x = Target2, y = RT2)) + geom_point() + geom_line(aes(group = 1)) 

How can I get the plot I want?

Uwe
  • 41,420
  • 11
  • 90
  • 134
  • 2
    Please read [how to make a reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). Hence, post some data and specify desired output: do you want both plots to be in one (not realistic, since you want different order of x-axis) or do you want to have the two in one plot (side-by-side)? – Tino Jan 17 '18 at 05:46
  • Possible duplicate of [Side-by-side plots with ggplot2](https://stackoverflow.com/questions/1249548/side-by-side-plots-with-ggplot2) – Tino Jan 17 '18 at 05:47
  • `library(tidyverse); bind_rows(set_names(df1, ~gsub('\\d', '', .x)), set_names(df2, ~gsub('\\d', '', .x)), .id = 'id') %>% ggplot(aes(Target, RT)) + geom_point() + geom_line() + facet_wrap(~id)` ...or something like that – alistaire Jan 17 '18 at 05:57

1 Answers1

2

One way to do it is to use sec_axis(). Here I have created two data frames. Both y-axis (RT1 and RT2) are on the same scale. Target1 and Target2 are on different scales.

df1 <- data.frame(Target1 = c(1,2,3), RT1 = c(1,2,3))
df2 <- data.frame(Target2 = c(20,30,40), RT2 = c(3,4,5))

To demonstrate the effect, I'm using scatter plot for df1 and line plot for df2. I also divide Target2 by 10 to bring the x variables closer and easier to be compared.

ggplot() +
  geom_point(data = df1, mapping = aes(Target1, RT1)) +
  geom_line(data = df2, mapping = aes(Target2/10, RT2)) +
  scale_x_continuous("Target 1", sec.axis = sec_axis(~.*10, name = "Target 2"))

Plot 1

or, if you don't want to rescsale the x-axis, you can use dup_axis() instead.

ggplot() +
  geom_point(data = df1, mapping = aes(Target1, RT1)) +
  geom_line(data = df2, mapping = aes(Target2, RT2)) +
  scale_x_continuous("Target 1", sec.axis = dup_axis(name = "Target 2"))

Plot 2

Hope it helps.

Lok
  • 41
  • 6