startz
June 27, 2023, 10:29pm
1
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
startz
June 28, 2023, 1:54am
3
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
.
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()`).
1 Like
startz
June 28, 2023, 3:05am
5
That is just so clever. Thanks.
1 Like
system
Closed
July 5, 2023, 3:06am
6
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.