manually set colors per group in barplot ggplot

故事扮演 提交于 2019-12-05 19:03:51

One option would be to create an hcl color palette with a different hue for each brand and a sequential luminosity that is the same for each month across different brands. For example:

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

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

Create color palette:

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]))

In the code below, we use fill=interaction(time, brand) to map a different color to each combination of brand and month. Then scale_fill_manual assigns the color palette we created above. The luminosity decreases for each month so that March is darker than February.

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) 

As an alternative to the plot above, a line plot might make it easier to compare the trends in each brand.

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()

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!