Search code examples
rplotscatter-plotggvis

Scatter plot in R with ggvis: how to plot multiple groups with different shape markers and corresponding fitted regression lines


To plot the following in R with the ggvispackage,

enter image description here

the code is

mtcars %>% 
  ggvis(~wt, ~mpg, fill = ~factor(cyl)) %>% 
  layer_points() %>% 
  group_by(cyl) %>% 
  layer_model_predictions(model = "lm")

If I change the fill to shape in the above, there would be an error:

Error: Unknown properties: shape.
Did you mean: stroke?

Why? How to achieve the desired outcome?


Solution

  • You have to specify the shape in the layer_points() call:

    mtcars %>% 
      transform(cyl = factor(cyl)) %>%
      ggvis(~wt, ~mpg) %>% 
      layer_points(shape = ~cyl, fill = ~cyl) %>% 
      group_by(cyl) %>% 
      layer_model_predictions(model = "lm", formula=mpg~wt)
    

    (Note that I use transform() to convert cyl into a factor. This means you don't have to convert cyl into a factor in the ggvis() call, and the plot key is a little bit neater.)


    enter image description here