问题
I am trying to plot a number of dimensions in r using plotly - is it possible to use both color and group parameters on factor variables to have a line that changes color?
Example:
grp <- c(letters[c(1,1,1,1,2,2,2,2)])
a <- c(1,2,3,4,2,3,4,5)
b <- c(1,3,5,6,1,2,4,4)
lvl <- c(1,1,2,2,1,1,2,2)
df <- data.frame(grp, a, b, lvl)
When plotting this using ggplot() I am able to create the desired effect as below, with grp as to define each line and lvl to define the color of sections of the line:
ggplot(data = df, aes(x = a, y = b, group = grp, color = lvl)) + geom_line() + geom_point()
However, when I then call ggplotly() the line gets grouped and colored by lvl.
回答1:
I'm searching for the same function. It seems that group and color is plotly kryptonite. So far my only solution is to make a column of color codes and use that to define the colors of the markers:
library(scales)
library(plotly)
grp <- c(letters[c(1,1,1,1,2,2,2,2)])
a <- c(1,2,3,4,2,3,4,5)
b <- c(1,3,5,6,1,2,4,4)
lvl <- c(1,1,2,2,1,1,2,2)
df <- data.frame(grp, a, b, lvl)
Palette <- data.frame(lvl = unique(df$lvl), color = brewer_pal("seq",palette = "Reds",direction = -1)(length(unique(df$lvl))), stringsAsFactors = FALSE)
df <- merge(x = df, y = Palette, by = "lvl")
p <- plot_ly(df, x = a, y = b, group = grp, mode = "markers+lines", marker = list(color = color, size = 8), line = list(color = "black", width = 2))
p
however this trick is very cumbersome and does not work with "line" that only takes a single color input and looks like this. HOWEVER if you do not give an input to the "line" it displays two different colors that you have no control over. like this
回答2:
I was trying to do the same thing and there is now an official way : you need to add a group_by statement before plot_ly (see https://github.com/ropensci/plotly/issues/418)
grp <- c(letters[c(1,1,1,1,2,2,2,2)])
a <- c(1,2,3,4,2,3,4,5)
b <- c(1,3,5,6,1,2,4,4)
lvl <- c(1,1,2,2,1,1,2,2)
df <- data.frame(grp, a, b, lvl)
df %>% group_by(grp) %>% plot_ly(x = a, y = b, mode = "markers+lines", color = lvl)
来源:https://stackoverflow.com/questions/35283743/using-both-group-and-color-in-plotly