Search code examples
rggvis

add a legend with multiple lines in GGVIS


I want to display multiple lines with ggvis.

Data

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

Code

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

The result is satisfactory, but I'm not able to add a legend nor to label somehow the three lines.

If I use add_legend I get an error:

    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

Solution

  • Here is my attempt. It has been a while since I used ggvis last time, but it seems that this is one way to deliver your expected outcome. You will end up seeing five lines using the following code. If necessary, subset your data and use the code.

    library(tidyr)
    library(ggvis)
    
    gather(df, variables, values, -(subfunctionname:label)) -> mydf
    
    
    ggvis(mydf, ~label, ~values, stroke = ~ variables) %>%
    layer_lines()
    

    enter image description here

    If you just want three factor levels with the colours you specified, the following would be one way.

    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