Using both group and color in plotly

元气小坏坏 提交于 2019-12-06 12:38:29

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

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)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!