【发布时间】:2021-12-29 05:31:27
【问题描述】:
我有一个样本数据集,其中包含周末日期和流失值,可以是负数,也可以是正数。在 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
【问题讨论】:
-
在将数据传递给ggplot之前将填充变量定义为一个因子。
-
这是否意味着 ggplotly 不支持这一点,我需要解决它在我的表中添加一个带有正确标签名称的因子列?
-
是的,据我所知不支持,这是最直接的解决方法。
-
谢谢,我想我会设法解决这个问题,但在此之前,我总是想确定是否真的需要我的解决方法,而不是因为我缺乏知识。
标签: r ggplot2 plotly r-plotly ggplotly