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

managing colors in R for plot.ly

我正在使用 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") 

这创建了我想要的图表,但是颜色没有正确应用到 trace。我希望其中一个条是红色的,另一个是绿色的,而线条是蓝色阴影。

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

我恢复了调用并添加了 inherit=FALSE:

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(data=dt, x = ~campaign_week, y = ~amount, color = ~category, type = "bar",
            colors = c("#00ff00", "#ff0000")) %>%
  add_trace( data=dt_net, x = ~campaign_week, y = dt_net$amount, type = "scatter",
            mode= "lines+markers",
            line = list(color = "#00AEFF"), name = "Net Income", inherit=FALSE) %>%
  layout(yaxis = y, barmode = "relative") 

图例还有问题:

基于 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") 

注意,这给出了警告,因为条形图轨迹继承了散点图的 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")