2017-08-09 9 views
3

私は関数を使っていくつかのPlotlyプロットを作成しようとしています。私はそれらのためのカラーパレットを作成しました。私が使用しているデータセットはグループ化係数の数が異なり、指定した順番で色を使用したいと考えていますが、いくつの要素があるかによって異なる順序を選択するようです。これを簡単に修正する方法はありますか?関数を作成する必要はありますか?ありがとうございました!R 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 

答えて

2

1つのオプションは、色を使用することである= PAL [1:長さ(G2)](第2の場合):

enter image description here

また、色を因子レベルと一致させることもできます。

+1

ありがとうございます!それは素敵な簡単な解決策です – jvilla

関連する問題