r - 如何根据 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()
这是我的代码。条的颜色会发生变化,但不会根据情况而变化。有人可以帮我吗?谢谢!
解决方案
主要问题是您必须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()
推荐阅读
- chrome-ux-report - 页面速度洞察是否会忽略没有索引的页面,没有添加跟踪标签以阻止机器人爬行
- javascript - 我怎样才能给表名加上别名?
- javascript - 我不明白为什么 firebase.auth().signInWithEmailAndPassword(email, password) 不起作用
- c++ - 抛出异常后在元素 4 处更改 C++ 数组值
- html - 使用 React Native 中的两个兄弟在屏幕 Flex Div 上居中对齐
- c# - OmniSharp.MSBuild.ProjectManager 尝试更新未加载的项目:csharp
- c++ - 使用模板化模板进行多重继承
- node.js - Mongoose 通过 id 查找递归嵌套对象
- python-3.x - 为什么kaggle API下载的-f开关不能识别传递给它的文件名作为字符串
- mysql - 如何查找在 Mysql 中执行失败事务的所有语句