2017-09-22 133 views
1

我需要爲barplot中的每個組手動設置顏色。我目前有填充=時間,這是目前確定的顏色。 我們有5個品牌和每個品牌2個獨立月份的值。我需要按品牌分組,但也需要一種方法來顯示哪個欄代表哪個月(時間),我目前可以做到這一點,但是我想爲每個欄組着色。例如。 brand1酒吧=紅色,brand2棒=藍色ECT,同時仍然有填補=時間在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調色板和不同品牌的每個月的順序亮度相同。例如:

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

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

創建調色板:

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)映射不同的顏色的品牌和月的每個組合。然後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