I wanted to make the column or bar color different depending on its values in ggplot2 Column Bar (eg. from light green to dark green or (green levels)).
I have a simple example that needed two modifications.
1) change the positive column to green and negative to red
2) make the color continuous from light to dark depending on the bar length
I tried to solve the first one but got an error. If you can help me to solve both, I will really appreciate that. Thanks in advance.
data.test <- data.frame(x = LETTERS[1:5],
y = c(-4, 2, 7, 3, -5),
z = c("Negative","Positive","Positive","Positive","Negative"))
ggplot(data.test, aes(x, y))
geom_col(position = "identity",aes(fill = z)) #
#scale_fill_manual(values = ifelse(data.test$y[1] > 0, c("#359206", "#de0025")
# ,c("#de0025","#359206")))
#the last two lines in the code is a trial to make positive green and negative red but it comes with an error as following :
Error in `f()`:
! Insufficient values in manual scale. 2 needed but only 1 provided.
Run `rlang::last_error()` to see where the error occurred.
Even though I provided 2 in my scale_fill_manual
.
CodePudding user response:
Since the "sign" of your data is already reflected in column y
, you can use it to fill your plot. What you need is scale_fill_gradient
, which allows gradient colouring of your plot.
library(ggplot2)
data.test <- data.frame(x = LETTERS[1:5],
y = c(-4, 2, 7, 3, -5),
z = c("Negative","Positive","Positive","Positive","Negative"))
ggplot(data.test, aes(x, y, fill = y))
geom_col()
scale_fill_gradient(low = "red", high = "green")
Created on 2022-04-12 by the reprex package (v2.0.1)