【问题标题】:How could I use specific colors to a combined plotly visualization in R?如何在 R 中使用特定颜色来组合绘图可视化?
【发布时间】:2020-09-23 09:27:40
【问题描述】:

我有两个data.frame如下:

df1 <- data.frame(
  week = c(rep(1, times = 3), rep(2, times = 3)),
  cat = rep(c("A", "B", "C"), times = 2),
  count = round(runif(6, 1, 10))
)

和

df2 <- data.frame(
  week = c(rep(1, times = 2), rep(2, times = 2)),
  cat = rep(c("E", "F"), times = 2),
  count = round(runif(4, 1, 10))
)

情节代码是

plotly::plot_ly(df1,x = ~week, y = ~count, type = "bar", split = ~cat) %>%
  add_trace(data = df2,x = ~week, y = ~count, type = "scatter", 
            mode = "lines", split = ~cat, yaxis = 'y2') %>%
  layout(title = 'Title',
         xaxis = list(title = ""),
         yaxis = list(side = 'left', title = 'var1', showgrid = FALSE, zeroline = FALSE),
         yaxis2 = list(side = 'right', overlaying = "y",
                       title = 'var2', showgrid = FALSE, zeroline = FALSE),
         showlegend = FALSE)

但我无法为每个组(A、B、C、E 和 F)指定特定颜色。我试图将color = ~cat, colors = c(A = "red", B = "green", C = "yellow") 用于条形图,同样用于线图。但不知何故,如果我只使用条形图或线图,它就不起作用了。

谢谢。

【问题讨论】:

    标签: r colors plotly


    【解决方案1】:

    建议在plot_ly 调用中定义颜色,然后使用col = ~cat 参数添加条形和线条。见下文:

    plotly::plot_ly(colors = c("A" = "red", "B" = "green", "C" = "yellow", "E" = "blue", "F" = "darkgreen")) %>% 
        add_bars(data = df1, x = ~week, y = ~count, type = "bar", color = ~cat) %>%
        add_trace(data = df2,x = ~week, y = ~count, type = "scatter", 
                  mode = "lines", color = ~cat, yaxis = 'y2') %>%
        layout(title = 'Title',
               xaxis = list(title = ""),
               yaxis = list(side = 'left', title = 'var1', showgrid = FALSE, zeroline = FALSE),
               yaxis2 = list(side = 'right', overlaying = "y",
                             title = 'var2', showgrid = FALSE, zeroline = FALSE),
               showlegend = FALSE)
    

    【讨论】:

    • 我想为每个类别 A、B、C、D、E 和 F 指定颜色。所以我也想为线条指定颜色。
    猜你喜欢
    • 2018-04-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-23
    • 2021-09-08
    • 1970-01-01
    • 1970-01-01
    • 2018-05-15
    相关资源
    最近更新 更多