Substitute color with patterns (stripes, lines) in bar ggplot - clustered data

773 Views Asked by At

I am trying to do a bar plot for grouped data, where each group has a pattern. Colors look rather ugly so I have tried substituting it with a pattern.

My data looks like this :

Time <- c(1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,6,6,  6,  6,  6, 11, 11 ,11, 11, 11)
 Group <- c("A",  "B", "C","D","E","A","B","C" ,"D","E","A","B","C","D","E","A","B","C","D","E","A", "B","C","D","E", "A","B","C","D","E") 
 Values <- c(38.4161807,  1.8280313, 34.1550423,  0.0000000, 37.2460332, 66.4168001 ,59.3746830 , 2.9191253,  5.6341807 , 3.5369600, 84.2639108, 11.1884641, 0.0000000 ,73.0754466  ,0.0000000, 60.5906227, 42.6958082  ,2.2462260 ,14.6034461,  1.4389593  ,2.2875870  ,1.4289716  ,0.0000000,  0.0000000, 0.8586154,  4.7177827 , 1.7227924 , 2.9949903 , 0.0000000 , 0.0000000)
 data <- c(Time, Group, Values)

I have used this to make colors in the bars:

ggplot(data, aes(x=as.factor(Time), y=Values, fill=Group )) +
geom_bar(stat="identity", position="dodge") +
scale_fill_manual(name="Group",
                      values=c("black", "Grey", "blue", "green", "yellow")) +
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
panel.background = element_blank(), axis.line = element_line(colour = "black"))

However, I want the bars filled by patterns like this for example:

enter image description here

I have tried ggpattern with both the pattern() and pattern_fill() functions but there are no changes at all.

2

There are 2 best solutions below

0
On
        library(ggpattern)
ggplot(data, aes(Time, Values)) +
  geom_col_pattern(
    aes(pattern = Group, pattern_angle = Group, pattern_spacing = Group), 
    fill            = 'white',
    colour          = 'black', 
    pattern_density = 0.35, 
    pattern_fill    = 'black',
    pattern_colour  = 'black'
  ) +
  scale_pattern_spacing_discrete(range = c(0.01, 0.05))

enter image description here

2
On

geom_bar_pattern() is what you are looking for which is in the ggpattern library

You will have to use ggplot2 to use ggpattern. The pattern instead of color is only available with the ggpattern library

EDIT

I get the same output as yuliaUU when formulating a solution

data <- data.frame(Time, Group, Values)

library(ggplot2)
library(ggpattern)
ggplot(data,aes(Time,Values)) +
    geom_col_pattern(aes(fill=Group),colour='blue',pattern='stripe') +
    theme_bw() +
    labs(title='Time - Group - Value') +
    theme(legend.key.size=unit(1.5,'cm'))

enter image description here