1
df <- data.frame(X1 = rep(1:5,1), X2 = rep(4:8,1), var1 = sample(1:10,5), row.names = c(1:5))
library("ggvis")
graph <- df %>%
        ggvis(~X1) %>%
        layer_lines(y = ~ var1) %>%
        add_axis("y", orient = "left", title = "var1") %>%
        add_axis("x", orient = "bottom", title = "X1")  %>%
        add_axis("x", orient = "top", title = "X2" )
graph

Obviously, the top x-axis (X2) is not correct here since it refers to the same variable as X1. I know how to create a scaled dual-y axis in ggvis. But how can I create a similar dual axis on different X? Those two X-axis should refer to different variables (X1 and X2 in this example).

I know this could be a really BAD idea to make dual X-axis. But one of my working dataset may need me to do so. Any comments and suggestions are appreciated!

Chuan
  • 667
  • 8
  • 22

1 Answers1

1

The second axis needs to have a 'name' in order for the axis to know which variable to reflect. See below:

df <- data.frame(X1 = rep(1:5,1), 
                 X2 = rep(4:8,1), 
                 var1 = sample(1:10,5), 
                 row.names = c(1:5))

library("ggvis")
df %>%
  ggvis(~X1) %>%
  #this is the line plotted
  layer_lines(y = ~ var1) %>%
  #and this is the bottom axis as plotted normally
  add_axis("x", orient = "bottom", title = "X1")  %>%
  #now we add a second axis and we name it 'x2'. The name is given
  #at the scale argument 
  add_axis("x", scale = 'x2',  orient = "top", title = "X2" ) %>%
  #and now we plot the second x-axis using the name created above
  #i.e. scale='x2'
  layer_lines(prop('x' , ~X2,  scale='x2'))

enter image description here

And as you can see the top x-axis reflects your X2 variable and ranges between 4 and 8.

Also, as a side note: You don't need rep(4:8,1) to create a vector from 4 to 8. Just use 4:8 which returns the same vector.

LyzandeR
  • 37,047
  • 12
  • 77
  • 87