Reputation: 3682
I have a dataset as this, and my goal is to make a bar chart and fill positive value with green, negative value with red:
df = data.frame(exp=c("A", "B", "C"), val = c(0.3,0.2,-0.1))
df$pos = df$val > 0
ggplot(df, aes(x=exp, y=val, fill=pos)) + geom_bar(stat="identity") + scale_fill_manual(values=c("red", "green"), guide=FALSE)
Above plot works as I expected. However, if my dataset happens to be all positive values:
df$val = c(0.3, 0.4, 0.5)
df$pos = df$val > 0
The same plotting will plot all positive value as "red" instead of "green", which is not what I want or expect. How do I fix this? TIA.
Upvotes: 0
Views: 86
Reputation: 98429
Inside the scale_fill_manual()
add that you need TRUE
values as green and FALSE
as red. If you just name color names then in case of only positive values there is only one level (TRUE
) and the first of two colors is used (is your case it is red).
ggplot(df, aes(x=exp, y=val, fill=pos)) + geom_bar(stat="identity") +
scale_fill_manual(values=c("FALSE"="red", "TRUE"="green"), guide=FALSE)
Upvotes: 2