r - 在 R Plotly 中定义调色板颜色顺序

标签 r plotly

我正在尝试使用函数创建许多 Plotly 图。我为他们创建了一个调色板。我使用的数据集具有不同数量的分组因素,我希望它们按照我指定的顺序使用颜色,但似乎根据因素的数量选择不同的顺序。有一个简单的方法可以解决这个问题吗?我需要创建一个函数吗?谢谢!

问题的直观示例 A visual example of the problem

library(plotly)
#Some example data
x <- 1:10
g <- c("A", "B", "C", "D", "E")
g2 <- c("A", "B")
g3 <- c("A", "B", "C")
y <- 1:20
df <- as.data.frame(cbind(x,g,y))
df2 <- as.data.frame(cbind(x,g2,y))
df3 <- as.data.frame(cbind(x,g3,y))

#Color palette
pal <- c('blue','yellow','green', 'pink', 'black')

#In this plot the order is as in the pal object, this is what I want.
plot1 <- plot_ly(data=df, x=~x, y=~y,
                 type = "bar", color=~g, colors =pal)
plot1

#In this plot uses the first and the fifth in the pal object
# and I would like to be the first and second colors.
plot2 <- plot_ly(data=df2, x=~x, y=~y,
                 type = "bar", color=~g2, colors =pal)
plot2

#In this one uses the first, the third and the fifth in that order
# and I would like to be the first, second and third colors.
plot3 <- plot_ly(data=df3, x=~x, y=~y,
                 type = "bar", color=~g3, colors =pal)
plot3

最佳答案

一种选择是使用colors = pal[1:length(g2)](对于第二种情况):

enter image description here

或者您可以将颜色与因子水平相匹配。

关于r - 在 R Plotly 中定义调色板颜色顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45587451/

相关文章:

python - 从 python 实现 R 包 TSdist

R 工作流 : How to handle hand-cleaning data

R plotly : Cannot re-arrange x-axis when axis type is category

python - 在绘图上显示数据框

javascript - 从node-red发送数据到本地网页

pandas - 使用plotly+cufflinks时,如何对DataFrame中的多个直方图使用特定的bin列表?

r - 如何在 R 中保留/重新评估 data.frame 的因子水平?

colorNumeric() 中的反转颜色

r - 通过解析或表达式定义表达式之间的区别

r - 带 Plotly 的树形图 : Blank Screen?