Hello,
scale_*_manual expects a discrete vector as values, you are passing it a
continuous one. The natural way of having a continuous variable set the
color and fill values is with a gradient scale.
I have changed geom_bar to geom_col.
Map prob to the fill aesthetic. Then, in scale_fill_continuous set low
and high values to
- the highest possible (all zeros is black).
- and to the lowest in the scale of probabilities (all binary ones or
hexa FF's is bright white)
Note that this reverses the real line order relation, you want to map
low probabilities to high binary/hexa values and vice-versa.
Don't mind the theme() setting a yellow panel background fill, it's just
meant to see better that the bars are in shades of gray.
library(ggplot2)
predictors <- c("x1", "x2", "x3",
"x4", "x5")
values <- c(1.0, 0.67, 0.26, 0.18, 0.17)
prob <- c(1.0, 0.001, 0.957, 0.924, 0.253)
df <- data.frame(predictors, values, prob)
ggplot(df, aes(x = predictors, y = values) ) +
geom_col(aes(fill = prob)) +
coord_flip() +
scale_fill_gradient(low = "#FFFFFF", high = "#000000") +
theme(panel.background = element_rect(fill = "yellow"))
If you want to use scale_fill_manual, create a vector of values first, then
- Map variable predictors to the fill aesthetic since each precitor
value has an associated probability prob;
- make values equal to gray_vals.
gray_vals <- setNames(gray(df$prob), df$predictors)
ggplot(df, aes(x = predictors, y = values) ) +
geom_col(aes(fill = predictors)) +
coord_flip() +
scale_fill_manual(values = gray_vals) +
theme(panel.background = element_rect(fill = "yellow"))
Hope this helps,
Rui Barradas
?s 15:07 de 28/06/2022, Md. Moyazzem Hossain escreveu:> Dear R- Experts,
>
> I hope that you are doing well.
>
> I am facing a problem with adding color to a barplot. My target is to add a
> bar color conditioning on the following
>
> Values close to 1 represent "White" and values tend to 0
represent "Black".
>
> However, I failed. The code is given below. I will be happy and thankful if
> anyone helps me in this regard.
>
> Thanks in advance.
>
> library(ggplot2)
> predictors=c("x1", "x2", "x3",
"x4", "x5")
> values=c(1.0, 0.67, 0.26, 0.18, 0.17)
> prob=c(1.0, 0.001, 0.957, 0.924, 0.253)
>
> df <- data.frame(predictors, values, prob)
> ggplot(df, aes(x=predictors, y=values) ) +
> geom_bar(stat="identity") +
> coord_flip()+
> scale_fill_manual(values=c("gray(prob)"))
>
> Best Regards,
>
> *Hossain*
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.