使用ggvis

时间:2015-11-24 07:21:45

标签: r ggvis multiple-axes

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

显然,顶部x轴(X2)在这里不正确,因为它指的是与X1相同的变量。我知道如何在ggvis中创建缩放的双y轴。但是如何在不同的X上创建类似的双轴?这两个X轴应该引用不同的变量(本例中为X1和X2)。

我知道制作双X轴可能是一个非常糟糕的想法。但是我的一个工作数据集可能需要我这样做。任何意见和建议表示赞赏!

1 个答案:

答案 0 :(得分: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")
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

正如您所看到的,顶部的x轴反映了您的X2变量,范围在4到8之间。

另外,作为旁注:您不需要rep(4:8,1)来创建从4到8的向量。只需使用返回相同向量的4:8