r - 在 R 中管理plot.ly 的颜色

标签 r plotly

我正在使用 plot.ly 库在 shiny 应用程序中进行交互式图表,但是我在管理图表中的颜色时遇到了一些麻烦。

使用plotly 4.3.5(来自github)的可重现示例:

library(data.table)
library(plotly)

dt <- data.table(campaign_week = c(1,2,3,1,2,3), category = c(rep("income",3),rep("cost",3)),
                 amount = c(100,50,35,-500,-20,-15))
dt_net <- dt[, .(amount = sum(amount)), by = campaign_week][,.(campaign_week, amount = cumsum(amount))]

y <- list(title = "Income", tickformat = "$,.0f",hoverformat = "$,.2f") 

plot_ly(dt_net, x = ~campaign_week, y = ~amount, type = "scatter",
        mode= "lines+markers",
        line = list(color = "#00AEFF"), name = "Net Income") %>%
  add_trace(data = dt, x = ~campaign_week, y = ~amount, color = ~category, type = "bar",
            colors = c("#00ff00", "#ff0000")) %>%
  layout(yaxis = y, barmode = "relative") 

这将创建我想要的图表,但是颜色未正确应用于跟踪。我预计其中一个条形为红色,另一个为绿色,而线条为蓝色。

编辑添加创建的plotly图表的屏幕截图

Current plotly output

最佳答案

基于https://plot.ly/r/bar-charts/#bar-chart-with-relative-barmode处的示例为每个类别单独的 add_trace 是可行的方法。

plot_ly(dt_net, x = ~campaign_week, y = ~amount, type = "scatter",
        mode= "lines+markers",
        line = list(color = "#00AEFF"), name = "Net Income") %>%
  add_trace(data =  dt[category=="income",] , x = ~campaign_week, y = ~amount,  type = "bar", name = "income",
            marker=list(color = "#00ff00")) %>%
  add_trace(data =  dt[category=="cost",] , x = ~campaign_week, y = ~amount,  type = "bar", name = "cost",
            marker=list(color = "#ff0000")) %>%
  layout(yaxis = y, barmode = "relative") 

enter image description here

请注意,这会发出警告,因为条形图跟踪继承了散点图的 modeline 属性,但条形图不支持这些属性。您可以忽略警告,也可以在分散之前调用条形图以避免它们......就像这样:

plot_ly() %>%
  add_trace(data =  dt[category=="income",] , x = ~campaign_week, y = ~amount,  type = "bar", name = "income",
            marker=list(color = "#00ff00")) %>%
  add_trace(data =  dt[category=="cost",] , x = ~campaign_week, y = ~amount,  type = "bar", name = "cost",
            marker=list(color = "#ff0000"))  %>%
  add_trace(data =  dt_net, x = ~campaign_week, y = ~amount, type = "scatter", mode= "lines+markers",
            line = list(color = "#00AEFF"), name = "Net Income") %>%
  layout(yaxis = y, barmode = "relative")

关于r - 在 R 中管理plot.ly 的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39584748/

相关文章:

r - 如何为 enquos 类型的 quosures 测试 null 或缺失

r - r项目中满足条件的元素向量

html - 计算 R 中前 10 名最常见作者的最佳方法

python - 如何获得 Plotly 图的 x 轴范围?

python - 有没有办法从正在运行的函数中检索局部变量?

r - 使用 dplyr 管道在 ggplot2 中动态 ylim

r - 将鼠标悬停在 Shiny 的 ggplot 上时的工具提示

python - Plotly:如何对两个不同图的类别使用相同的颜色?

python - 绘制随绘图动态变化的多个轴

python - 可以阴谋地返回帐户的现有数字列表吗?