Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading