plotly 否决了 ggplot2 的 scale_fill_manual 的标签

plotly overrules ggplot2's scale_fill_manual's labels

我有一个示例数据集,其中包含周末日期和流失值,可以是负值也可以是正值。在 ggplot2 中,我在值的符号上使用 scale_fill_manual() 作为组。 这可以很好地显示正值与负值的颜色。标签也会根据提供的标签进行重写。但是,如果我只是将其制作成绘图图,我会丢失标签,它们会被设置回 -1, 1 因子。确实不支持这一点,如果支持的话,这是他们完成这项工作的另一种方式

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

plot_ggplotly <- ggplotly(plot_ggplot)

plot_ggplotly

这样做有用吗?

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)

编辑:我刚刚看了评论,我认为这是建议的