R在y轴ggplot中按值绘制颜色

时间:2017-08-29 12:20:31

标签: r ggplot2

我想在X轴上的名称和y轴上的Average_Working_hours之间创建一个ggplot图。 如何根据平均工作时间的价值填充栏中的颜色? 我的数据如下所示:

enter image description here

如果某人工作时间超过8小时,应该用红色填充,否则用蓝色填充?

那是我的代码:

ggplot(Report, aes(x=Report$Name,y=Report$average_working_hours)) + ggtitle('working hours in July') + ylab(' working hours')+ geom_bar(stat = 'identity', fill = ifelse(Report$average_working_hours > 8){"red"} else {"blue"})+ theme_gray()

给我警告:

In if (Report$average_working_hours > 8) { :
  the condition has length > 1 and only the first element will be used

并且所有栏都填充了蓝色:

enter image description here

2 个答案:

答案 0 :(得分:0)

不需要ifelse语句,只需编写条件然后使用scale_fill_manual:

ggplot(Report, aes(x=Report$Name,y=Report$average_working_hours)) + 
  ggtitle('working hours in July') + 
  ylab(' working hours') + 
  geom_bar(stat = 'identity', aes(fill = Report$average_working_hours > 8)) + 
  theme_gray() + 
  scale_fill_manual(values=c('blue', 'red'))

答案 1 :(得分:0)

这可以非常简单地使用dplyr完成。

我要做的第一件事是创建一列“ Working hours> 8”,然后使用该值填写ggplot,如下所示:

Report %>% 
 mutate(larger_than_8 = ifelse(Report$average_working_hours > 8, 1, 0)) %>%
 ggplot(., aes(x = Name, y = average_working_hours, fill = larger_than_8)) +
 geom_bar(stat = 'identity') + 
 theme_gray() + 
 scale_fill_manual(values=c('blue', 'red')) + 
 ggtitle('working hours in July') + 
 ylab('working hours')

您可以将ifelse语句中的二进制分类更改为要在图例中显示的任何文本。