I'd like to plot a regression line using ggplot and then add dots for a small subset of the observations, the latter selected by a particular column in my tibble being true. Probably obvious, but not to me at the moment.
Any advice gratefully received.
library(ggplot2) mtcars$four <- ifelse(mtcars$cyl == 4,TRUE,FALSE) mtcars |> ggplot(aes(mpg,drat)) + geom_point() + geom_smooth(method = "lm", se = FALSE) + theme_minimal() #> `geom_smooth()` using formula = 'y ~ x'
mtcars |> ggplot(aes(mpg,drat)) + geom_point(mapping = aes(color = four)) + geom_smooth(method = "lm", se = FALSE) + theme_minimal() #> `geom_smooth()` using formula = 'y ~ x'
mtcars |> ggplot(aes(mpg,drat, color = four)) + geom_point() + geom_smooth(method = "lm", se = FALSE) + theme_minimal() #> `geom_smooth()` using formula = 'y ~ x'
Created on 2023-06-27 with reprex v2.0.2
Thanks @technocrat, but that's not quite what I want. I want one regression line done with all the data but the points shown only for four==TRUE.
four==TRUE
library(ggplot2) mtcars$four <- ifelse(mtcars$cyl == 4, TRUE,FALSE) ggplot(mtcars, aes(mpg,drat)) + geom_point(mapping = aes(color = ifelse(four, "red", NA))) + geom_smooth(method = "lm", se = FALSE) + scale_color_identity() + theme_minimal() #> `geom_smooth()` using formula = 'y ~ x' #> Warning: Removed 21 rows containing missing values (`geom_point()`).
That is just so clever. Thanks.
This topic was automatically closed 7 days after the last reply. New replies are no longer allowed. If you have a query related to it or one of the replies, start a new topic and refer back with a link.