【问题标题】:Make dual X-axs based on different variables using ggvis使用 ggvis 根据不同的变量制作双 X 轴
【发布时间】:2015-11-24 07:21:44
【问题描述】:
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 轴可能是一个非常糟糕的主意。但是我的一个工作数据集可能需要我这样做。感谢任何 cmets 和建议!

【问题讨论】:

    标签: r ggvis multiple-axes


    【解决方案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'))
    

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

    另外,附带说明:您不需要 rep(4:8,1) 来创建从 4 到 8 的向量。只需使用返回相同向量的 4:8

    【讨论】:

    • 非常感谢!正好解决我的问题。
    • 非常欢迎@ChuanTang。很高兴我能帮上忙:)
    猜你喜欢
    • 2019-09-04
    • 1970-01-01
    • 2022-01-13
    • 2016-01-24
    • 1970-01-01
    • 2014-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多