在barplot ggplot中手动设置每组的颜色

时间:2017-09-22 01:25:43

标签: r ggplot2 plotly

我需要在条形图中为每个组手动设置颜色。我目前有填充=时间,这是目前确定的颜色。 我们有5个品牌和每个品牌2个月的价值。我需要按品牌分组,但还需要一种方法来显示哪个条形代表哪个月(时间),我现在可以这样做但是我想为每个条形组着色。例如。 brand1 bars = red,brand2 bars = blue ect,同时仍然有fill = time

这是我的代码:

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)

1 个答案:

答案 0 :(得分:3)

一种选择是为每个_site创建一个具有不同色调的hcl调色板,并为不同品牌的每个月创建相同的亮度。例如:

brand

创建调色板:

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)指定我们在上面创建的调色板。每个月的光度都会下降,因此3月份比2月份更暗。

scale_fill_manual

enter image description here

作为上图的替代方案,线图可以更容易地比较每个品牌的趋势。

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