Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 510
dwstu Avatar asked Aug 31 '14 10:08

dwstu


People also ask

How do you make a scatter plot with two sets of data in R?

How to make a scatter plot in R? You can create scatter plot in R with the plot function, specifying the x values in the first argument and the y values in the second, being x and y numeric vectors of the same length.

How do you group data in a scatter plot?

If you have a grouping variable you can create a scatter plot by group passing the variable (as factor) to the col argument of the plot function, so each group will be displayed with a different color.

How do you make a scatterplot with a regression line in R?

A scatter plot can be created using the function plot(x, y). The function lm() will be used to fit linear models between y and x. A regression line will be added on the plot using the function abline(), which takes the output of lm() as an argument. You can also add a smoothing line using the function loess().

How do you plot one variable against another in R?

To plot a scatterplot of one numeric variable against another numeric variable we just need to include both variables as arguments when using the plot() function.


1 Answers

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

like image 154
Andrie Avatar answered Oct 03 '22 03:10

Andrie