Ollie
Ollie

Reputation: 157

ggplot2 Change color of specific bar in R

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")

enter image description here

Upvotes: 1

Views: 909

Answers (2)

help-info.de
help-info.de

Reputation: 7260

Without creating an extra column you may want to use

library(ggplot2)

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(aes(fill = score < 60), stat='identity')+
  scale_fill_manual(guide = "none", breaks = c(FALSE, TRUE), values=c("dodgerblue", "firebrick1")) +  
  labs(x = "Student_name" , y = "math_score")

resulting in

enter image description here

Upvotes: 1

Quinten
Quinten

Reputation: 41225

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

Upvotes: 3

Related Questions