Search code examples
rggvisdensity-plot

Is it possible to combine density plots of two separate variables with ggvis


I feel like I've searched everywhere for this but essentially I have time series data of multiple numeric variables and I wanted to create one single plot that has then density function of two or variables on it.

So essentially I have:

df %>% ggvis(~y1) %>% layer_densities()
df %>% ggvis(~y2) %>% layer_densities()

but if I do something like:

df %>% ggvis(~y1) %>% layer_densities() %>% layer_densities(~y2)

I get the following error:

Error in eval(expr, envir, enclos) : object 'y2' not found

I feel like this shouldn't be too difficult but I can't figure it out, I don't think I am supposed to use group by because these are two seperate variables with no similar factors or characteristics. Any help would be appreciated.


Solution

  • You can work-around by reshaping your dataset so you have a grouping variable in one column and the values of both columns you want to plot in another. I do the work via melt from reshape2.

    library(reshape2)
    df2 = melt(df, measure.vars = c("y1", "y2"))
    

    Once you do that you can use group_by to get a separate density layer for each variable.

    df2 %>% group_by(variable) %>% 
        ggvis(~value) %>% 
        layer_densities()