我有一个包含 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))
我明白了:
如何使散射和相应轨迹的颜色相同?
这不是我所需要的:
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
关于r - 通过因子 plotly R 绘制和跟踪相同的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48083643/