I have already used the code for plotting-
ggplot(mpg, aes (x= displ, y= hwy))
geom_point()
and the scatter plot has already been obtained. However, I want to highlight the bottom right points that are different from the general linear trend of the plotting.
CodePudding user response:
Another option is using the package ggrepel with geom_label_repel
function. You can create a label of what you want per point if necessary. You can change the condition to whatever you want. I added a linear line using geom_smooth
. Here is a reproducible example:
library(dplyr)
library(ggplot2)
library(ggrepel)
# create highlight dataframe
highlight_df <- mpg %>% filter(displ > 6 & hwy > 20 & hwy < 30)
# Create certain label
highlight_df$your_label <- "label"
ggplot(mpg, aes(x= displ, y= hwy))
geom_point()
geom_smooth(method = "lm", se = FALSE)
geom_label_repel(highlight_df, mapping = aes(x = displ, y = hwy, label = your_label), color = "red", segment.color = "grey")
#> `geom_smooth()` using formula 'y ~ x'
Created on 2022-08-23 with reprex v2.0.2
CodePudding user response:
It may be useful:
library(ggplot)
library(gghighlight)
ggplot(mpg)
geom_point(aes(displ, hwy))
gghighlight(displ > 5, hwy > 17)
CodePudding user response:
https://cmdlinetips.com/2019/05/how-to-highlight-select-data-points-with-ggplot2-in-r/
highlight_df <-mpg%>%
filter(hwy>=20,displ>=5)
ggplot(mpg, aes (x= displ, y= hwy)) geom_point(alpha=0.3)
geom_point(data=highlight_df,aes(x=displ,y=hwy),color='red',size=3)