Home > Software engineering >  plotly overrules ggplot2's scale_fill_manual's labels
plotly overrules ggplot2's scale_fill_manual's labels

Time:11-18

I have a sample data set containing a end of week date and a churn value, either be negative or positive. In ggplot2 I use the scale_fill_manual() on the sign of the value as group. This works perfectly fine showing the colors for positive versus negative values. Also the labels get rewritten according to the labels provided. However if I simply make it a plotly graph I lose my labels and they are set back to the -1, 1 factors instead. Does plotly not support this and if so is their another way to get this done

library(ggplot2)
library(plotly)

dt <- structure(list(date = structure(c(18651L, 18658L, 18665L, 18672L, 
18679L, 18686L, 18693L, 18700L, 18707L, 18714L), class = c("IDate", 
"Date")), churn = c(-3.27088948787062, -0.582518144525087, -0.125024925224327, 
-0.333746898263027, -0.685714285714286, -0.340165549862042, 0.0601176470588235, 
-0.119351608461635, -0.0132513279284316, -0.011201854099989)), row.names = c(NA, 
-10L), class = c("data.table", "data.frame"))

plot_ggplot <- ggplot(dt, aes(x = date, y = churn * 100))  
  geom_bar(stat = "identity", aes(fill = factor(sign(churn))))  
  scale_fill_manual(
    values = c("#4da63f", "#e84e62"),
    breaks = c("-1", "1"),
    labels = c("Growing base", "Declining base")
  )  
  ylim(-75, 25)  
  labs(
    title = "Weekly churn rate",
    fill = "Legend"
  )
plot_ggplot

ggplot output image

plot_ggplotly <- ggplotly(plot_ggplot)

plot_ggplotly

plotly output image

CodePudding user response:

Does this do the trick?

dt$base = ifelse(sign(dt$churn)>0, "Growing base","Declining base")
plot_ggplot <- ggplot(dt, aes(x = date, y = churn * 100))  
  geom_bar(stat = "identity", aes(fill = base))  
  scale_fill_manual(
    values = c("#4da63f", "#e84e62"),
    )  
  ylim(-75, 25)  
  labs(
    title = "Weekly churn rate",
    fill = "Legend"
  )
plot_ggplot
plot_ggplotly <- ggplotly(plot_ggplot)

enter image description here

edit: I just read the comment, I think it is what was suggested

  • Related