rggplot2colorsbar-chart

geom_bar color according to 2 vars


I was looking how to set colors in the geom_bar ggplot2 function, but havn't seen yet similar data here a repro:

rm(list=ls())
library(ggplot2)
set.seed(123)
data=data.frame(hit=sample(1:3,20,replace = TRUE),
                type=sample(c("A","B","C"),20,replace=TRUE))
ggplot(data,aes(hit,fill=type))+
  geom_bar(stat="count",position=position_dodge())

my_bar_chart

I need to have some gradient from A to C and different colors from 1 to 3.


Solution

  • I think the following works for you which uses transparency to differentiate between the types:

    library(ggplot2)
    
    set.seed(123)
    data <- data.frame(hit = sample(1:3, 20, replace = TRUE),
                       type = sample(c("A", "B", "C"), 20, replace = TRUE))
    
    ggplot(data) +
      geom_bar(aes(hit, alpha = type, fill = as.factor(hit)),
               stat = "count", position = position_dodge()) +
      scale_fill_manual(name = "Hit", 
                        values = c("darkblue", "darkgreen", 'darkred')) +
      scale_alpha_discrete(name = "Type", 
                           breaks = c("A", "B", "C"), 
                           range = c(0.3, 1))
    

    I also would recommend to have the complete dataset when plotting:

    library(dplyr)
    library(tidyr)
    library(ggplot2)
    
    data %>% 
      summarize(count = n(), .by = c(hit, type)) %>% 
      complete(hit, type = unique(type), fill = list(count = 0)) %>% 
    ggplot() +
      geom_bar(aes(hit, count, alpha = type, fill = as.factor(hit)),
               stat = "identity", position = position_dodge()) +
      scale_fill_manual(name = "Hit", 
                        values = c("darkblue", "darkgreen", 'darkred')) +
      scale_alpha_discrete(name = "Type", 
                           breaks = c("A", "B", "C"), 
                           range = c(0.3, 1))