2017-08-29 87 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