4

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

ismirsehregal
  • 30,045
  • 5
  • 31
  • 78
Merijn van Tilborg
  • 5,452
  • 1
  • 7
  • 22

1 Answers1

2

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

elielink
  • 1,174
  • 1
  • 10
  • 22
  • 1
    Thanks to work out the suggestion given, it solves indeed the outcome of my plot. also good to know I actually have to use this work around as ggplotly does not support the breaks / levels like ggplot does in `scale_*_manual()` – Merijn van Tilborg Nov 18 '21 at 10:40