在绘图中同时使用组和颜色 [英] Using both group and color in plotly

查看:65
本文介绍了在绘图中同时使用组和颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用plotly在r中绘制多个尺寸-是否可以在因子变量上同时使用colorgroup参数以使线改变颜色?

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?

示例:

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)

使用ggplot()进行绘制时,我可以创建如下所示的效果,使用grp定义每条线,使用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()

但是,当我再呼叫ggplotly()时,该行被分组为,并用lvl着色.

However, when I then call ggplotly() the line gets grouped and colored by lvl.

推荐答案

我正在搜索相同的函数.看来组和颜色是密谋k石. 到目前为止,我唯一的解决方案是创建一列颜色代码,并使用它来定义标记的颜色:

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

这篇关于在绘图中同时使用组和颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆