Plotly - Two colors mix to one color but should not when using color labels

Viewed 46

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!

1 Answers

You have to make sure that your label is a factor containing both levels.

Thus, the following line will render the second plot nicely:

set.seed(1)
## make sure that label is a factor containing both levels
## even if there is just one level in the data
d2 <- data.frame(category = as.factor(seq(10)), diff = runif(10, min=20, max=50)) %>% 
  mutate(label = factor(ifelse(diff <= 0, "green", "red"), c("green", "red"))) 

d2 %>% 
  plot_ly(x=~diff, y=~category, type = 'bar', orientation = 'h', 
          color = ~label, colors = c("#009C48", "#E61414")) 
Related