ggplot2 geom_col填充给出看似随机的结果

时间:2017-12-18 00:05:06

标签: r ggplot2

我正在绘制一些数据,我想根据阈值突出显示某些列,但geom_col似乎是随机分配颜色。

dass21_scores_plot %>%    
ggplot(aes(dassId, score, label=score)) 
    + geom_col(fill = 
    ifelse(dass21_scores_plot$score == -1, "blue1", 
        ifelse(dass21_scores_plot$measure == "Depression Baseline" && dass21_scores_plot$score > 27, "red", 
            ifelse(dass21_scores_plot$measure == "Anxiety Baseline" && dass21_scores_plot$score > 19, "red", 
                ifelse(dass21_scores_plot$measure == "Stress Baseline" && dass21_scores_plot$score > 33, "red", "green4")))))
    + geom_text(aes(label = ifelse(score > -1, as.integer(score), ''), vjust = ifelse(score > 21, 2, -1)), size = 4) 
    + theme(axis.text.x = element_text(size = 10, angle = 90))
    + facet_wrap(~measure, ncol = 4)

这就是我得到的。

enter image description here

这对我来说并不是很有意义,因为即使是具有相同特征的列也会被填充不同。列没有没有绘制的属性。有什么明显的东西我不见了吗?

1 个答案:

答案 0 :(得分:0)

我使用@joran的建议修复了它。

这是我的新代码:

colours <- as.character(c())
for(i in 1:length(dass21_scores_plot$dassId)) {
    x = substr(dass21_scores_plot$measure[i], 1, 3)
    s = dass21_scores_plot$score[i]
    if (s == -1) {
        colours[i] = "b"
    } else if(x == "Dep"){
        colours[i] = ifelse(s >= 28, "r", "g")
    } else if(x == "Anx"){
        colours[i] = ifelse(s >= 20, "r", "g")
    } else if(x == "Str"){
        colours[i] = ifelse(s >= 34, "r", "g")
    }
}
dass21_scores_plot$col <- colours

dass21_scores_plot %>%    
ggplot(aes(dassId, score, label=score)) + geom_col(aes(fill = col), show.legend = F) 
+ geom_text(aes(label=ifelse(score>-1, as.integer(score), ''), vjust = ifelse(score>21, 2, -1)), size=4) 
+ theme(axis.text.x = element_text(size = 10, angle = 90)) + facet_wrap(~measure, ncol=4) 
+ scale_fill_manual(values = c("blue", "green4", "red"))