首页 > 解决方案 > 如何根据 R 中 ggplot 中的条件更改条形的颜色?

问题描述

df <-data.frame(BA_5287)

question <- df$Type.of.Question 
submission <- df$Students.submitted
score <- df$Score.Correctly

cond <- ifelse(abs(score)>94,'darkgreen',
               ifelse(abs(score)<0.94 & abs(score) >=0.7,'yellow','red'))

graph <- ggplot(data=df,
                aes(x=Question,y=Score))+geom_bar(stat = "identity",
                                                  color='blue',
                                                  fill=cond)
graph + coord_flip()

这是我的代码。条的颜色会发生变化,但不会根据情况而变化。有人可以帮我吗?谢谢!

标签: rggplot2colorsbar-chart

解决方案


主要问题是您必须aes()在该geom_bar行中使用另一个并在其中调用fill参数。然后,正如上面提到的@dc37,您只需要使用scale_fill_identity.

需要注意的另一件事是,您不需要像在问题中那样定义数据框之外的变量。您可以简单地通过它们的列名来调用它们。

这是一个示例,其中包含一些虚构的数据

library(dplyr)
library(ggplot2)

df <- data.frame(question  = LETTERS[1:15],
                 score = rnorm(15, 90,5))

using 比嵌套的 ifelse 语句case_when更易于阅读。

  df <- df %>%
  mutate(cond = case_when(
    score > 94 ~ 'darkgreen',
    score < 0.7 ~ 'red',
    TRUE ~ 'yellow'   #anything that does not meet the criteria above
  ))

aes()然后您可以在调用中使用填充geom_bar并添加scale_fill_identity

ggplot(data = df, aes(x = question, y =score)) +
  geom_bar(stat = "identity", color = 'blue', aes(fill = cond)) +
  scale_fill_identity() +
  coord_flip()

在此处输入图像描述


推荐阅读