2017-09-22 18 views
1

バープロットの各グループの色を手動で設定する必要があります。私は現在、塗りつぶし=時間があり、これは現在色を決定しています。 私たちは5つのブランドを持ち、ブランドごとに2つの別々の月の値を持っています。私はブランド別にグループ化する必要がありますが、どのバーがどの月(時間)を表すかを表示する方法が必要ですが、私は現在これを行うことができますが、各バーグループに色付けしたいと思います。例えば。 brand1バー=赤、brand2バー=まだここbarplot ggplotでグループごとに手動で色を設定する

を埋める=時間持つながら電気ショック療法の青色が私のコードです:

colors <- c("#98999B", "#F4C400", "#CB003D", "#6BABE5", "#E65400", "#542C82") 

time <- c("February 2017","March 2017","February 2017","March 2017","February 2017","March 2017","February 2017","March 2017","February 2017","March 2017") 
value <- as.numeric(c("3.08","3.64","1.61","1.81","-1.02","-1.09","-5.23","-5.08","-1.51","-1.43")) 
brand <- c("brand1","brand1","brand2","brand2","brand3","brand3","brand4","brand4","brand5","brand5") 

Monthly_BMS_df <- as.data.table(cbind(time,value,brand)) 

bar <- ggplot(Monthly_BMS_df, aes(brand, value, fill = time)) + 
    geom_bar(stat="identity", position = "dodge") + 
theme(legend.position='none') + scale_fill_manual(values=colors) 

ggplotly(bar, width=1000,height=350) 

答えて

2

一つのオプションは、各brandに異なる色合いでhclカラーパレットを作成することですし、連続した光度は、異なるブランド間で毎月同じです。例:以下のコードで

nb = length(unique(Monthly_BMS_df$brand)) 
nm = length(unique(Monthly_BMS_df$time)) 

colors = apply(expand.grid(seq(70,40,length=nm), 100, seq(15,375,length=nb+1)[1:nb]), 1, 
       function(x) hcl(x[3],x[2],x[1])) 

、私たちはブランドと月の組み合わせごとに異なる色をマッピングするために fill=interaction(time, brand)を使用します。

library(ggplot2) 
library(data.table) 
library(plotly) 

Monthly_BMS_df <- data.table(time, value, brand) 

は、カラーパレットを作成します。次に、scale_fill_manualは、上記で作成したカラーパレットを割り当てます。明度は月ごとに減少し、3月は2月よりも暗くなります。上記のプロットに代わるものとして

bar <- ggplot(Monthly_BMS_df, aes(brand, value, fill=interaction(time, brand))) + 
    geom_hline(yintercept=0, colour="grey60") + 
    geom_bar(stat="identity", position = "dodge", show.legend=FALSE) + 
    scale_fill_manual(values=colors) + 
    theme_classic() 

ggplotly(bar, width=1000, height=350) 

enter image description here

、ラインプロットは、簡単に各ブランドの傾向を比較することになるかもしれません。

library(dplyr) 

ggplot(Monthly_BMS_df, aes(time, value, group=brand, colour=brand)) + 
    geom_hline(yintercept=0, colour="grey60") + 
    geom_text(data=Monthly_BMS_df %>% filter(time==min(time)), 
      aes(label=brand), position=position_nudge(-0.25)) + 
    geom_line(linetype="12", alpha=0.5, size=0.7) + 
    geom_text(aes(label=value)) + 
    guides(colour=FALSE) + 
    theme_classic() 

enter image description here

関連する問題