Reputation: 968
I have the following data:
df1 <- data.frame(col1 = rep(LETTERS[1:3], each = 4), col2 = rnorm(12), col3 = runif(12), col4 = rep(c("Fred", "Bob"), each = 6))
df1_list <- split(df1, df1$col1)
I'm trying to make a separate plot for each list element and arrange them in the same figure:
lapply(df1_list, function (arg1) {
plotly::plot_ly(arg1, x = ~col2, y = ~col3, color = ~col4) %>%
layout(showlegend = T)
}) %>%
subplot()
The problem is that the colors are not consistent across each plot. I'd like points representing Fred
always to be the same color, and the same should go for points representing Bob
.
Is there a way to ensure groups get the same color across all these plots?
Thanks!
Upvotes: 0
Views: 336
Reputation: 124658
One option would be to use a named color vector which assigns a color to each name like so:
set.seed(123)
df1 <- data.frame(col1 = rep(LETTERS[1:3], each = 4),
col2 = rnorm(12),
col3 = runif(12),
col4 = rep(c("Fred", "Bob"), each = 6))
df1_list <- split(df1, df1$col1)
colors <- RColorBrewer::brewer.pal(3, "Set2")[c(1, 3)]
names(colors) <- c("Fred", "Bob")
library(plotly)
lapply(df1_list, function (arg1) {
plotly::plot_ly(arg1, x = ~col2, y = ~col3, color = ~col4, colors = colors) %>%
layout(showlegend = T)
}) %>%
subplot()
Upvotes: 1