[英]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?我想更改条形的颜色并且条件得分低于 60。我在哪里设置我的条件并着色? 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")
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:您可以创建一个额外的列,使用
case_when
告诉您的条件,并将该列分配给您使用 scale_fill_identity fill
的geom_bar
, scale_fill_identity
所示:
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使用reprex v2.0.2创建于 2022-09-11
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导致
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.