R plotly - 绘制分组图表时如何修复颜色

时间:2017-10-25 14:58:25

标签: r colors bar-chart plotly

我尝试使用相同的功能 grp 分组绘制重叠的线条和条形图。 我需要为线条和条纹使用固定颜色。

首次添加条形图时,它的效果很好:

library(plotly)

df <- data.frame(year = rep((2000:2017), each=2),
             grp = rep(c("Grp1", "Grp2"), 18),
             y1 = rnorm(36, 100, 40),
             y2 = rnorm(36, 50, 10)
             )


plot_ly(df) %>% 
   add_trace( x = ~year, y = ~y1, 
           type = 'bar', 
           yaxis = "y2",
           opacity = .4, 
           color = ~grp, 
           colors = colorRamp(c("grey", "black"))) %>%
   add_trace(x = ~year, y = ~y2, 
           type = 'scatter', 
           mode = 'lines+markers', 
           linetype = ~grp,
           line = list(color = "red")) %>% 
   layout(yaxis2 = list(overlaying = "y",
                     side = "right")) 

enter image description here

但如果我切换条形跟踪和线条跟踪,我对条形图的颜色选择就会消失。

  plot_ly(df) %>% 
     add_trace(x = ~year, y = ~y2, 
          type = 'scatter', 
          mode = 'lines+markers', 
          linetype = ~grp,
          line = list(color = "red")) %>% 
     add_trace( x = ~year, y = ~y1, 
           type = 'bar', 
           yaxis = "y2",
           opacity = .4, 
           color = ~grp, 
           colors = colorRamp(c("grey", "black"))) %>%
     layout(yaxis2 = list(overlaying = "y",
                     side = "right")) 

enter image description here

显然我的语法不正确:是否有人知道如何正确编写此代码以确保颜色在任何顺序都是稳定的?

非常感谢!

1 个答案:

答案 0 :(得分:0)

尝试在colors内指定plot_ly

plot_ly(df, colors = colorRamp(c("grey", "black"))) %>% 
  add_trace(x = ~year, y = ~y2, 
       type = 'scatter', 
       mode = 'lines+markers', 
       linetype = ~grp,
       line = list(color = "red")) %>% 
  add_trace( x = ~year, y = ~y1, 
       type = 'bar', 
       yaxis = "y2",
       opacity = .4, 
       color = ~grp) %>%
  layout(yaxis2 = list(overlaying = "y",
       side = "right")) 

enter image description here