2017-08-29 84 views
-1

我想用g轴绘制X轴名称和Y轴平均工作时间之间的图。 如何填充颜色取决于平均工作时间值的酒吧? 我的数据如下所示:R在y轴上绘制颜色值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

+1

为了能够正确地回答你的问题,它会帮助很多,如果你能为我们提供一些更多的信息。请根据这里的信息编辑你的问题:[如何制作一个很好的R可重现的例子?](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/ 5963610)和这里:[我怎么问一个好问题?](https://stackoverflow.com/help/how-to-ask) – 4rj4n

回答

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')) 
+0

从'aes()'部分中删除'Report $'。在'Report'被声明为原始的'ggplot()'函数中的数据之后,它不再需要,事实上可以搞砸了。 – Matt74