0

I want to make a plot with ggplot between Names in X-axis and Average_Working_hours in y-axis. How can I fill the bar with colors depended in the value of average working hours? My data looks like the following:

enter image description here

If someone works for more than 8 hours, the bar should be fill with red, otherwise fill with blue?

That's my code:

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()

gived me the warning :

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

and all the bar is filled with blue:

enter image description here

jhoepken
  • 1,842
  • 3
  • 17
  • 24
  • 1
    To be able to answer your question properly, it'd help a lot if you could provide us with some more information. Please edit your question based on the info here: [How to make a great R reproducible example?](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610) and here: [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask) – 4rj4n Aug 29 '17 at 12:58

2 Answers2

0

No need for ifelse statement, just write your condition and then use 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'))
Vincent K
  • 568
  • 5
  • 9
  • remove the `Report$` from your `aes()` part. After `Report` is declared as the data in the original `ggplot()` function, it is no longer needed, and in fact can mess things up. – Matt74 Aug 29 '17 at 22:36
0

This can be done quite simply using dplyr.

First thing I would do is create a column, "Working hours > 8" then use that value is the fill in ggplot as follows:

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

You can change the binary classification in the ifelse statement to any text you'd like to show in the legend.