绘图r中的色线与标记分开

时间:2018-10-10 13:44:42

标签: r plotly

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

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

这给了我 enter image description here

当我更改标记输入时,例如:

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

但是随后线的颜色也改变了,我希望它们保持绿色和红色。 enter image description here

我试图在脚本的不同位置放置“颜色”。我还看到了他们在其中添加add_trace的帖子,并且我尝试了过滤add_trace中的数据的不同方法,但是它给出了一个错误,因此我没有正确地进行操作。

有人可以帮助我吗?非常感谢!

1 个答案:

答案 0 :(得分: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"))

必须是一种更快的方法,但至少可以使用:)