I want to change the color of bar and condition is score below 60.
Where do I set my condition,and color it? Thanks for helping.
set.seed(123)
df = data.frame(Student = sample(state.name, 10), score = sample(1:100, 10, replace=T))
ggplot(df, aes(Student, score)) +
geom_bar(stat='identity')+
labs(x = "Student_name" , y = "math_score")
>Solution :
You could create an extra column which tells your condition using case_when and assign that column to your fill in geom_bar with scale_fill_identity like this:
set.seed(123)
df = data.frame(Student = sample(state.name, 10), score = sample(1:100, 10, replace=T))
library(ggplot2)
library(dplyr)
df %>%
mutate(color = case_when(
score < 60 ~ "red",
TRUE ~ "Grey"
)) %>%
ggplot(aes(Student, score)) +
geom_bar(aes(fill = color), stat='identity') +
scale_fill_identity() +
labs(x = "Student_name" , y = "math_score")

Created on 2022-09-11 with reprex v2.0.2
