0
votes

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

2
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? and here: How do I ask a good question?4rj4n

2 Answers

0
votes

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

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.