【问题标题】:Color lines in plotly r separately from markersplotly r 中的颜色线与标记分开
【发布时间】:2019-03-15 10:50:27
【问题描述】:

我正在尝试找到一种方法来保持我的绘图图中线条的颜色,即使标记颜色发生变化。我将解释...一个示例数据集:

mtcars$vs<-as.factor(mtcars$vs)
mtcars$gear<-as.factor(mtcars$gear)
mtcars$Date<-sample(seq(as.Date('2016/01/01'), as.Date('2018/01/01'), by="day"), 32)

我做了一个我想要的情节:

pal <- c("red", "blue", "green")

mtcars %>% 
  group_by(vs) %>%
  mutate(fit = fitted(loess(mpg ~ as.numeric(Date))))%>%
  plot_ly(x = ~Date, 
          colors=pal, showlegend = T) %>%
  add_markers( y = ~mpg, color= ~vs, alpha = 0.4) %>%
  add_lines(y = ~fit, color = ~vs,line=list(width=4), colors=pal) %>%
  layout(xaxis = list(title="Date"), title="All")

这给了我

当我更改标记输入时:

mtcars %>% 
  group_by(vs) %>%
  mutate(fit = fitted(loess(mpg ~ as.numeric(Date))))%>%
  plot_ly(x = ~Date, 
          colors=pal, showlegend = T) %>%
  add_markers( y = ~mpg, color= ~gear, alpha = 0.4) %>%
  add_lines(y = ~fit, color = ~vs,line=list(width=4), colors=pal) %>%
  layout(xaxis = list(title="Date"), title="All")

但随后线条颜色也会改变,我希望它们保持绿色和红色......

我尝试将“颜色”放在脚本中的不同位置。我还看到他们添加了add_trace 的帖子,我尝试了不同的方法来过滤 add_trace 中的数据,但它给出了一个错误,所以我没有以正确的方式进行操作..

谁能帮帮我?将不胜感激!

【问题讨论】:

    标签: r plotly


    【解决方案1】:

    找到了!真的有点傻,只是用错了颜色代码:

    df1<-mtcars%>%  
      filter(vs=="0")%>%
      mutate(fit1 = fitted(loess(mpg ~ as.numeric(Date))))
    
    df2<-mtcars%>%  
      filter(vs=="1")%>%
      mutate(fit2 = fitted(loess(mpg ~ as.numeric(Date))))
    
    
      plot_ly(mtcars, x = ~Date, 
              showlegend = T) %>%
      add_markers( y = ~mpg, color= ~vs) %>%
      add_lines(data=df1, y = ~fit1, line = list(color = 'rgb(22, 88, 229)')) %>%
      add_lines(data=df2, y = ~fit2, line = list(color = 'rgb(226, 124, 6)')) %>%
      layout(xaxis = list(title="Date"))
    
      plot_ly(mtcars, x = ~Date, 
              showlegend = T) %>%
        add_markers( y = ~mpg, color= ~gear) %>%
        add_lines(data=df1, y = ~fit1, line = list(color = 'rgb(22, 88, 229)')) %>%
        add_lines(data=df2, y = ~fit2, line = list(color = 'rgb(226, 124, 6)')) %>%
        layout(xaxis = list(title="Date"))
    

    必须是一种更快的方法,但至少它有效:)

    【讨论】:

      猜你喜欢
      • 2016-10-21
      • 2020-09-19
      • 1970-01-01
      • 1970-01-01
      • 2020-08-16
      • 2021-01-02
      • 1970-01-01
      • 2015-06-22
      • 1970-01-01
      相关资源
      最近更新 更多