颜色Map在R中无法使用plotly

des4xlb0  于 2023-06-19  发布在  其他
关注(0)|答案(1)|浏览(108)

我有一个像这样的数据框

df1 <- data.frame("time" = 1:10, A1 = rnorm(10), B1 = rnorm(10), C1 = rnorm(10), D1 = rnorm(10))
df2 <- data.frame("time" = 1:5, A2 = rnorm(5), B2 = rnorm(5),  C2 = rnorm(5), D2 = rnorm(5))

我想绘制df1,x轴为“时间”,y轴为所有其他变量。类似地,我想在x轴上绘制df2,在y轴上绘制所有其他变量。在本例中,我希望线是“点”,标记是空心圆。我指定了要使用的以下颜色

my_colors <- c(             ## add the standard plotly colors
  'red',  
  'blue',  
  'green',  
  'yellow'
)

下面是我尝试过的plotly代码

longDF1 <- melt(df1, id.vars = "time")
longDF2 <- melt(df2, id.vars = "time")
  
  plot_ly() %>%
  add_trace(data = longDF1, x = ~time, y = ~value, type = 'scatter', mode = 'lines+markers', color = ~variable,
            line = list(color = my_colors, dash = 'solid'),
            marker = list(color = my_colors, symbol = 'circle')) %>% 
  add_trace(data = longDF2, x = ~time, y = ~value, type = 'scatter', mode = 'lines+markers', color = ~variable,
            line = list(color = my_colors, dash = 'dot'),
            marker = list(color = my_colors, symbol = 'circle-open'))

颜色似乎没有被添加到情节中。相反,plotly会生成自己的颜色。有什么解决办法吗?

2hh7jdfx

2hh7jdfx1#

要获得所需的颜色,请从linemarker规范中删除color属性,并将颜色向量传递给colors属性,只需将其传递给第一个跟踪或直接在plot_ly()中传递,如下所述。此外,当你有八个不同的类别复制你的颜色矢量,即。使用colors = c(my_colors, my_colors)

library(plotly)

set.seed(123)

plot_ly(colors = c(my_colors, my_colors)) %>%
  add_trace(
    data = longDF1, x = ~time, y = ~value, type = "scatter", mode = "lines+markers", color = ~variable,
    line = list(dash = "solid"),
    marker = list(symbol = "circle")
  ) %>%
  add_trace(
    data = longDF2, x = ~time, y = ~value, type = "scatter", mode = "lines+markers", color = ~variable,
    line = list(dash = "dot"),
    marker = list(symbol = "circle-open")
  )

相关问题