Search code examples
rggvis

How to make multiple smoothing lines in ggvis?


This is the code to produce a line chart with a smoother

mtcars %>% 
    ggvis(~wt, ~mpg) %>%
    layer_lines() %>%
    layer_smooths()

And this factorizes by vs and plot two lines of to different colors:

mtcars %>% 
    ggvis(~wt, ~mpg, stroke= ~ as.factor(vs)) %>%
    layer_lines()

But how I can add two different smoothers as well? I am trying this but don't understand why it won't work

mtcars %>% 
    ggvis(~wt, ~mpg, stroke= ~ as.factor(vs)) %>%
    layer_lines() %>%
    layer_smooths()

Solution

  • You can set grouping with dplyr::group_by:

    library(dplyr)
    library(ggvis)
    
    mtcars %>% 
        mutate(vs = factor(vs)) %>%
        ggvis(~wt, ~mpg, stroke = ~vs) %>%
        group_by(vs) %>% 
        layer_lines() %>%
        layer_smooths()
    

    plot with two smooths