0

I know how we can have a plot with two y-axis and common x but I was wondering how I can have a plot for two x-axes and two y-axes.

x1<-seq(10,20,1)
y1<-seq(30,40,1) 
x2<-seq(0.1,1.1,0.1)
y2<-seq(40,50,1) 
A<-data.frame(x1,y1,x2,y2)
Sarah
  • 15
  • 2

2 Answers2

0

You can convert the data frame from wide to long and then use facet_grid:

library(ggplot2)
library(tidyr)
library(dplyr)
x <- data.frame(x1, x2)
y <- data.frame(y1, y2)

y <- y %>%
  gather(key = y_axis, value = y_value, y1, y2)
x <- x %>%
  gather(key = x_axis, value = x_value, x1, x2)
A <- cbind(x, y)
ggplot(A, aes(x_value, y_value)) +
  facet_grid(y_value ~ x_value) +
  geom_point()    #can replace with geom_line() if you prefer a line to points 
tbradley
  • 2,210
  • 11
  • 20
  • 1
    Please reduce your `library` load to only those packages actually needed; `tidyverse` is a convenience super-package to bring in many many other packages that aren't required here. In this case, I think it would be `dplyr`, `tidyr`, and `ggplot2`. – r2evans Apr 14 '17 at 22:24
0

Give the plot a bit more space on the right so that the label of the second y axis fits. Then plot the first dots normally. Afterwards plot the second series over it without axes. Then add the other axes and the axes labels.

par(mar = c(5.4,4.1,4.1,5.4))
plot(x1,y1,xlab="red",ylab="red",col="red")
par(new = T)
plot(x2,y2,xaxt="n",xlab="",yaxt="n",ylab="")
Axis(side = 3, at = x2, labels = x2)
mtext(side = 3, line = 3, 'black')
Axis(side = 4, at = y2, labels = y2)
mtext(side = 4, line = 3, 'black')

Be sure to somehow indicate which dots are which with colour or text or something.

See the this for an example. I changed y2 to decrease so that actually both dot series are visible:

y2<-seq(50,40,-1)
guscht
  • 843
  • 4
  • 20