I want to have a bar plot that colors the bars red if the numbers are positive and green if the numbers are negative. I want this to be in the form of a ggplot "template" where I can change the underlying data and it still does what I want. Currently my code only works if all the numbers are positive or if there are positive and negative numbers in my data.
Version 1 (does not work). All bars should be green, however, since there are no positive numbers the fill = change < 0
does not work and it takes just the first color which is red in this case.
data1 <- data.frame(group = as.factor(c("all", "men", "women")),
change = as.numeric(c(-10000, -6000, -4000)))
ggplot(data1,
aes(x = group,
y = change,
fill = change < 0)) +
geom_bar(stat = "identity") +
scale_fill_manual(guide = FALSE,
values = c("red", "green"))
Version 2 (works as expected).
data2 <- data.frame(group = as.factor(c("all", "men", "women")),
change = as.numeric(c(2000, 6000, -4000)))
ggplot(data2,
aes(x = group,
y = change,
fill = change < 0)) +
geom_bar(stat = "identity") +
scale_fill_manual(guide = FALSE,
values = c("red", "green"))
Version 3 (works - by chance?). All bars are red but I guess as in Version 1 this is only the case because red comes first in the colors specified in scale_fill_manual
?
data3 <- data.frame(group = as.factor(c("all", "men", "women")),
change = as.numeric(c(10000, 6000, 4000)))
ggplot(data3,
aes(x = group,
y = change,
fill = change < 0)) +
geom_bar(stat = "identity") +
scale_fill_manual(guide = FALSE,
values = c("red", "green"))
How can I specify the bar color to make it work as I want, regardless if I use data1, data2 or data3 as an input?