Home > Mobile >  Change colour of geom_point for maximum y value
Change colour of geom_point for maximum y value

Time:08-01

I have a data frame that looks like this:

Salary        Year
15             1990
16             1991
15             1992
20             1993
17             1994
19             1995

Which I plot using the ggplot.


Dataframe %>%
   ggplot(aes(Year, Salary))  
   geom_line()   
   geom_point()

Which results in this graph:

enter image description here

What I want to do is to mark the point who is at salary 20 in a black circle (like it is right now) while the rest of the points are white circles with a black ring. How do I do that?

CodePudding user response:

An option is to add a second call with geom_point on the subset of dataset

library(dplyr)
library(ggplot2)
Dataframe  %>%
   ggplot(aes(Year, Salary))  
     geom_line()   
     geom_point()  
     geom_point(data = Dataframe %>% filter(Salary != max(Salary)),
      pch = 21, fill = "white", colour = "black")

-output

enter image description here

data

Dataframe <- structure(list(Salary = c(15L, 16L, 15L, 20L, 17L,
 19L), Year = 1990:1995), class = "data.frame", row.names = c(NA, 
-6L))

CodePudding user response:

Use a binary variable (a condition) as fill aesthetics.
And shape = 21. From the help page ?points:

pch = 21: filled circle

x<-'Salary        Year
15             1990
16             1991
15             1992
20             1993
17             1994
19             1995'
Dataframe <- read.table(textConnection(x), header = TRUE)

library(ggplot2)

ggplot(Dataframe, aes(Year, Salary, fill = Salary == 20, group = 1))  
  geom_line()   
  geom_point(shape = 21)  
  scale_fill_manual(values = c(`FALSE` = 'white', `TRUE` = 'black'))

Created on 2022-07-31 by the reprex package (v2.0.1)

  • Related