当使用set运算符映射fill时,ggvis legend将消失

时间:2015-10-05 18:55:31

标签: r legend ggvis

我希望能够创建如下所示的水平堆叠条形图。

    df = data.frame(name = c("A","A","B","B","C","C"),
                    low = c(3,9,2,7,5,10),
                    high = c(9,12,7,13,10,16),
                    type = c("X","Y","X","Y","X","Y"))

    df %>% ggvis(~low,~name) %>% layer_rects(x2 = ~high,height = band(),fill = ~type) %>% 
add_axis('x',title = "Value")

但是,我想将自己的自定义颜色映射到“Type”变量。当我使用set运算符时,图例消失:

df = data.frame(name = c("A","A","B","B","C","C"),
                low = c(3,9,2,7,5,10),
                high = c(9,12,7,13,10,16),
                type = c("red","blue","red","blue","red","blue"))

df %>% ggvis(~low,~name) %>% layer_rects(x2 = ~high,height = band(),fill := ~type) %>% 
  add_axis('x',title = "Value")

有谁知道如何解决这个问题?

R version 3.1.3 (2015-03-09)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252    LC_MONETARY=English_United States.1252
[4] LC_NUMERIC=C                           LC_TIME=English_United States.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] ggvis_0.4.1   ggplot2_1.0.1 tidyr_0.2.0   plyr_1.8.1    dplyr_0.4.1  

loaded via a namespace (and not attached):
 [1] assertthat_0.1   colorspace_1.2-6 DBI_0.3.1        digest_0.6.8     grid_3.1.3       gtable_0.1.2    
 [7] htmltools_0.2.6  httpuv_1.3.2     jsonlite_0.9.16  lazyeval_0.1.10  magrittr_1.5     MASS_7.3-39     
[13] mime_0.3         munsell_0.4.2    parallel_3.1.3   proto_0.3-10     R6_2.0.1         Rcpp_0.11.5     
[19] reshape2_1.4.1   RJSONIO_1.3-0    rstudio_0.98.484 rstudioapi_0.3.1 scales_0.2.4     shiny_0.11.1    
[25] stringr_0.6.2    tools_3.1.3      xtable_1.7-4  

1 个答案:

答案 0 :(得分:0)

你有(至少)两个选择。如果您只想更改绘图和图例中的颜色,可以使用scale_*函数之一作为属性fill。对于字符变量,您可以使用scale_nominal

df = data.frame(name = c("A","A","B","B","C","C"),
             low = c(3,9,2,7,5,10),
             high = c(9,12,7,13,10,16),
             type = c("X","Y","X","Y","X","Y"))

df %>% ggvis(~low, ~name) %>% 
    layer_rects(x2 = ~high, height = band(), fill = ~type) %>% 
    add_axis('x', title = "Value") %>%
    scale_nominal("fill", range = c("red", "blue"))

enter image description here

将set运算符与第二个数据集一起使用,您需要先通过scale_nominal添加比例,然后才能通过add_legend添加图例。您将使用values中的add_legend参数来定义颜色映射到的值。

df2 = data.frame(name = c("A","A","B","B","C","C"),
                low = c(3,9,2,7,5,10),
                high = c(9,12,7,13,10,16),
                type = c("red","blue","red","blue","red","blue"))

df2 %>% ggvis(~low, ~name) %>% 
    layer_rects(x2 = ~high, height = band(), fill := ~type) %>% 
    add_axis('x',title = "Value") %>%
    scale_nominal("fill", range = c("red", "blue")) %>%
    add_legend(scales = "fill", values = c("Xvalue", "Yvalue"))

enter image description here

这都是使用ggvis_0.4.2完成的,我没有检查自0.4.1以来发生了什么变化。