r - 通过因子 plotly R 绘制和跟踪相同的颜色

标签 r plotly

我有一个包含 3 个因素的散点图。我添加了 3 个跟踪,其中每个跟踪对应一个因子。我希望散点图和轨迹的颜色相同。这是生成适当测试数据的简单函数:

## generate test data
getTestData <- function(seed_val=711, noise=1.0) {
    set.seed(seed_val)
    d <- seq(as.Date('2017/01/01'), as.Date('2017/01/08'), "days")
    first_name <- rep("Jane", 8)
    first_name <- append(first_name, rep("Fred", 8))
    first_name <- append(first_name, rep("Sally", 8))
    y1_vals <- seq(1, 3*8, 1)
    y2_vals <- rnorm(3*8, mean=y1_vals, sd=noise)
    dat <- data.frame(date=d, f_name=first_name, y1=y1_vals, y2=y2_vals,
                      stringsAsFactors = FALSE)
    return(dat)
}

如果我创建一个数据框并将其传递给 plot_ly 像这样:
library(plotly)
library(dplyr)
df <- getTestData()
p1 <- plot_ly(df, x=~date, y=~y1, color=~f_name,
          type = 'scatter', mode = "lines+markers") %>% 
      layout(yaxis = list(title = "some important y value")) %>% 
      add_trace(y=~y2, name='actual', showlegend=TRUE, 
          type='scatter', mode='lines',
          line=list(width = 2, dash = 'dash', color=~f_name))

我明白了:

enter image description here

如何使散射和相应轨迹的颜色相同?

这不是我所需要的:
Grouped line plots in Plotly R: how to control line color?

这非常接近:
Same color assigned to same level of factor in R plotly
但是这个答案的作者准确地指出了我在尝试各种黑客时遇到的问题:

Note that hav[ing] factor variables can mess this up due to the ordering that plotly uses (which I can't decipher sometimes).

最佳答案

你在寻找这样的东西:

pal <- c("red", "blue", "green")
p1 <- plot_ly(df, x=~date, y=~y1, color=~f_name, colors = pal,
              type = 'scatter', mode = "lines+markers") %>% 
    layout(yaxis = list(title = "some important y value")) %>% 
    add_trace(y=~y2, name='actual', showlegend=TRUE, 
              type='scatter', mode='lines',
              line=list(width = 2, dash = 'dash'), color=~f_name, colors = pal)
p1

enter image description here

关于r - 通过因子 plotly R 绘制和跟踪相同的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48083643/

相关文章:

r - 我们可以将 S3 灵活性与 S4 表示检查结合起来吗?

python - 在 Plotly Express 散点图中将所有标记设置为相同的固定大小

javascript - 减少 Plotly.js 库的大小

r - 如何在 R-plotly 等高线图中添加 X 标签、Y 标签、z 标签

R 中的 rbind() 函数在合并的数据帧中生成 NA

r - 如何用R删除字符串中的反斜杠

r - 在应用族函数中使用反引号和运算符

r - Selectizeinput 输入互斥 R Shiny

r - Plotly 绘图不会在 RMarkdown 文档的 for 循环内渲染

python - plotly 尖峰未出现在次要 plotly 上