I have a barplot that should color the bars above 0 as red and bars below 0 as green. This works fine if my data includes numbers + and - 0.
library(ggplot2)
library(plotly)
set.seed(1)
plot1 <- data.frame(category = as.factor(seq(10)), diff = runif(10, min=-50, max=50)) %>% # negative and positive numbers
mutate(label = ifelse(diff <= 0, "green", "red")) %>%
plot_ly(x=~diff, y=~category, type = 'bar', orientation = 'h',
color = ~label, colors = c("#009C48", "#E61414"))
plot1
However, as this plot is used within a shiny app and the data varies, sometimes the data only includes numbers + or - 0
Then, the two colors are mixed together to an ugly brown. Like here:
set.seed(1)
plot2 <- data.frame(category = as.factor(seq(10)), diff = runif(10, min=20, max=50)) %>% # only positive numbers
mutate(label = ifelse(diff <= 0, "green", "red")) %>%
plot_ly(x=~diff, y=~category, type = 'bar', orientation = 'h',
color = ~label, colors = c("#009C48", "#E61414"))
plot2
In plot 2 the bars should be red, as all bars are above 0. Anyone has an idea how to fix that? I need a solution that is independent works for data with positive and/or negative numbers.
Thanks for your help!