在GGVIS中添加多行的图例

时间:2015-05-05 00:21:35

标签: r ggvis

我想用ggvis显示多行。

数据

    df <- read.table(header = TRUE, text = "
  subfunctionname activityname label activityunits activityhours ftehours avFteHours wlFteHours
 North    IncidentPriority0   01-Jan  3950 3 36244 18122 11850
 North    IncidentPriority0   02-Feb  0 3 32800 16400   0
 North    IncidentPriority0   03-Mar  0 3 36408 18204 0
 North    IncidentPriority0   04-Apr  0 3 35096 17548 0
 North    IncidentPriority0   05-May  0 3 36244 18122 0
 North    IncidentPriority0   06-Jun  0 3 35260 17630   0
 North    IncidentPriority0   07-Jul  0 3 36285 18142.5 0
 North    IncidentPriority0   08-Aug  0 3 36326 18163 0
 North    IncidentPriority0   09-Sep  0 3 35137 17568.5 0
 North    IncidentPriority0   10-Oct  0 3 36203 18101.5 0
 North    IncidentPriority0   11-Nov  3721 3 35260 17630 11163
 North    IncidentPriority0   12-Dec  3947 3 36285 18142.5 11841
")

代码

library(ggvis)
df %>% 
   ggvis( ~label,  ~avFteHours) %>% layer_lines() %>%
   layer_lines( ~label,   ~wlFteHours, stroke:="blue") %>%
   layer_lines( ~label,   ~ftehours, stroke:="red") 

结果令人满意,但我无法添加图例,也无法以三行标记。

如果我使用add_legend,我会收到错误:

    df %>% 
   ggvis( ~label,  ~avFteHours) %>% layer_lines() %>%
   layer_lines( ~label,   ~wlFteHours, stroke:="blue") %>%
   layer_lines( ~label,   ~ftehours, stroke:="red") %>%
   add_legend()

   Error: length(scales_props) not greater than 0

1 个答案:

答案 0 :(得分:2)

这是我的尝试。我上次使用ggvis已经有一段时间了,但似乎这是实现预期结果的一种方法。您最终将使用以下代码看到五行。如有必要,请对数据进行子集化并使用代码。

library(tidyr)
library(ggvis)

gather(df, variables, values, -(subfunctionname:label)) -> mydf


ggvis(mydf, ~label, ~values, stroke = ~ variables) %>%
layer_lines()

enter image description here

如果您只想要使用指定颜色的三个因子级别,则以下是单向。

library(dplyr)
library(tidyr)
library(ggvis)

gather(df, variables, values, -(subfunctionname:label)) %>%
filter(variables %in% c("avFteHours", "wlFteHours", "ftehours")) %>%
droplevels -> mydf

ggvis(mydf, ~label, ~values, stroke = ~ variables) %>%
layer_lines() %>%
scale_nominal("stroke", range = c("red", "black", "blue"))

enter image description here