To plot the following in R with the ggvis
package,
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?
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.
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.
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().
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.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With