Search code examples
rggplot2graphgeom-bar

Make the color of specific bars more solid than others in R


I am creating a bar chart considering two years and a set of countries. To do this, I am using the geom_bar function from the ggplot package. I would like to highlight the colors for a specific country only. Is there a way to do that?

Here's an example of the chart, which is similar to what I'm working on:

Panel <- read.dta("http://dss.princeton.edu/training/Panel101.dta")
Panel$y = Panel$y / 1000000

Panel %>%
  filter(year %in% c(1990, 1991)) %>% 
  ggplot(mapping = aes(x = country, y = y, fill = as.factor(year))) +
  geom_bar(stat = 'identity',
           position = 'dodge2', colour = 'white') +
  scale_fill_manual(values = c('#001d87', '#d9912e')) +
  labs(fill = 'Year', x = 'Country') +
  theme_classic()

The goal is to highlight the colors for country C, for instance, by making the colors for this country more solid compared to the others, something that can differentiate this country without affecting the legend. I would like to highlight the color and not just the border. I appreciate any assistance!

enter image description here


Solution

  • You can use alpha to highlight the countries you want like this

    Panel <- read.dta("http://dss.princeton.edu/training/Panel101.dta")
    Panel$y = Panel$y / 1000000
    
    Panel %>% mutate(country_alpha=ifelse(country %in% c("C"),1,0.5)) %>% 
      filter(year %in% c(1990, 1991)) %>% 
      ggplot(mapping = aes(x = country, y = y, fill = as.factor(year), alpha=country_alpha)) +
      geom_bar(stat = 'identity',
               position = 'dodge2', colour = 'white') +
      scale_fill_manual(values = c('#001d87', '#d9912e')) +
      labs(fill = 'Year', x = 'Country') +
      theme_classic()