Search code examples
rggplot2ggvis

ggvis: add size property to a line


Just getting started with ggvis. Not a particularly interesting or general question I'm afraid, but its is not obvious to me how to add a size property to a line. In particular, how would I replicate the following plot using ggvis?

library(ggplot2)

df <- data.frame(
  id = c(1,1,1,2,2,2,2),
  x  = c(1,2,3,1,2,3,4),
  y  = c(2,3,4,1,1,2,3)
)

ggplot(df, aes(x, y, colour = as.factor(id), size = id)) +
  geom_line()

Also, could someone with a high enough reputation create a ggvis tag? Cheers.


Solution

  • The following:

    library(ggvis)
    
    gg <- ggvis(df, props(~x, ~y, stroke = ~factor(id)))
    gg <- gg + layer_line(props(strokeWidth := ~id*4))
    gg
    

    produces:

    plot

    I had to tweak the multiplier for the strokeWidth to get it to be a bit thicker, but that should be a good starting point for you. Remember ggivs is based on Vega so getting familiar with the terminology in that new graphics grammar is going to almost be a requirement to understand how to "think" in ggvis.

    Here's an example of doing this more properly (and more ggplot2-like with scale_quantitative:

    gg <- ggvis(df, props(~x, ~y, stroke = ~factor(id)))
    gg <- gg + layer_line(props(strokeWidth = ~id)) 
    gg <- gg + scale_quantitative("strokeWidth",
                                  trans="linear", 
                                  domain=range(df$id), 
                                  range=c(1,10))
    gg
    

    sq

    Doing a ?scale_quantitative or reviewing the "scales" online examples should give you a good idea of your options for getting the desired effect.

    I also should point out the use of "=" vs ":=" in the second example. From the ggvis site:

    The props() function uses the = operate for mapping (scaled), and the := operator for setting (unscaled). It also uses the ~ operator to indicate that an expression should be evaluated in the data (and in ggvis, the data can change); without the ~ operator, the expression is evaluated immediately in the current environment.