Home > database >  Fill ggplot barchart variable's category to alternate colour by variable
Fill ggplot barchart variable's category to alternate colour by variable

Time:12-02

I have a dataset with values, for variables, with each categorized into 3 observation categories.

Below is a minimum working example:

library(dplyr)
library(ggplot2)
Test.df <-c()
Test.df$Value <- runif(51)
Test.df <- as.data.frame(Test.df)
Test.df$Category <- as.factor(c("A", "B", "C"))
Test.df <- arrange(Test.df, Category)
Test.df$Variable <- c("ZA", "ZB", "ZC", "ZD", "ZE", "ZF", "ZF", "ZH", "ZI", "ZJ", "ZK", "ZL", "ZM", "ZN", "ZO", "ZP", "ZQ")

Colors <- c("#E8223D","#E4B533","#4BA046","#C7202F","#EF402C","#27BFE5","#FBC413","#A21C43","#F26A2D","#DE1768","#F99D29","#BF8D2C","#407F46","#1E97D4","#5ABA47","#136A9F","#15496B")

Bar.Plot <-
  ggplot(Test.df, aes(x = Variable, y = Value))  
  geom_bar(stat="identity",
           width = 0.9,
           position = position_dodge(width = 1), 
           aes(fill = Category))   
  scale_fill_manual(Test.df$Variable, values=Colors)

Bar.Plot

This outputs the following plot:

example plot

How can the colors alternate by variable, so that variable ZA's 3 observations are the same color, variable ZB's 3 observations are the next color, and each variable iterates down the list for colors?

Additionally, is it possible to add an alpha for each observation to add some transparency e.g. to have a different alpha for each of the three ZA observations?

CodePudding user response:

Besides fill, there is also the group aesthetic:

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
library(ggplot2)

Test.df <- c()
Test.df$Value <- runif(51)
Test.df <- as.data.frame(Test.df)
Test.df$Category <- as.factor(c("A", "B", "C"))
Test.df <- arrange(Test.df, Category)
Test.df$Variable <- c("ZA", "ZB", "ZC", "ZD", "ZE", "ZF", "ZF", "ZH", "ZI", "ZJ", "ZK", "ZL", "ZM", "ZN", "ZO", "ZP", "ZQ")

Colors <- c("#E8223D", "#E4B533", "#4BA046", "#C7202F", "#EF402C", "#27BFE5", "#FBC413", "#A21C43", "#F26A2D", "#DE1768", "#F99D29", "#BF8D2C", "#407F46", "#1E97D4", "#5ABA47", "#136A9F", "#15496B")


Bar.Plot <-
  ggplot(Test.df, aes(x = Variable, y = Value))  
  geom_bar(
    stat = "identity",
    width = 0.9,
    position = position_dodge(width = 1),
    aes(fill = Variable, group = Category, alpha = Category)
  )  
  scale_fill_manual(Test.df$Variable, values = Colors)  
  guides(alpha = FALSE)
#> Warning: `guides(<scale> = FALSE)` is deprecated. Please use `guides(<scale> =
#> "none")` instead.

Bar.Plot
#> Warning: Using alpha for a discrete variable is not advised.

Created on 2021-12-02 by the enter image description here

  • Related