当使用 set 运算符映射 fill 时,ggvis 图例消失

ggvis legend disappears when fill is mapped with the set operator

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

    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" 变量。当我使用集合运算符时,图例消失了:

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  

你有(至少)两个选择。如果您只想更改绘图和图例中的颜色,可以使用 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"))

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

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"))

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