Home > Back-end >  How to make different patterns and colors in different category of data using ggplot in R?
How to make different patterns and colors in different category of data using ggplot in R?

Time:01-03

I would like to make my data have different colors for species and different patterns for sex. However, I can only set to make it different colors according to the sex. Here is my data, enter image description here

CodePudding user response:

You can use ggpattern to get different patterns per sex and different colors per species:

library(ggplot2)
library(ggpattern)

ggplot(data_summary, aes(x = species, y = mean, fill = species, group = sex))   
  geom_col_pattern(position = "dodge", aes(pattern = sex), 
                   pattern_fill = "white", pattern_color = "white",
                   pattern_angle = 45, show.legend = FALSE)   
  geom_errorbar(aes(ymin=mean-sd, ymax=mean sd), position = position_dodge(0.9), 
                width = 0.2, show.legend = FALSE)  
  labs(x = NULL, y = NULL)   
  theme_classic()   
  theme(panel.border = element_rect(linewidth = 0.5, fill = NA))   
  ylim(0, 80)  
  scale_fill_manual(values = c("#870A30" ,"#D3D3D3"))

enter image description here

CodePudding user response:

There is a nice package called ggpattern which offers hatching for geoms. Unfortunately it is not available for the R version I am using.

But I would like to offer different alpha values for the fill color.

The alpha itself can defined like scale_alpha_manual(values = c(.5,1)).

library(ggplot2)

data_summary <- read.table(text = "
  species,sex,mean,sd,tukey
  species_a,female,67,4.17,a
  species_b,male,62.2,4.8,a
  species_b,female,61.3,6.43,a
  species_a,male,49.7,16.2,a
", header = T, sep = ','
  
)


# coloured barplot
ggplot(data_summary, aes(x = factor(species), y = mean, fill = sex, alpha = species))   
  geom_bar(stat = "identity", position = "dodge", show.legend = FALSE)   
  geom_errorbar(aes(ymin=mean-sd, ymax=mean sd), position = position_dodge(0.9), width = 0.2, show.legend = FALSE)  
  labs(x="", y="")   theme_bw()   
  theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank())  
  theme(legend.position = c(0.1, 0.75))   ylim(0, 80)  
  scale_fill_manual(values=c("#870A30","#D3D3D3"))  
  scale_alpha_manual(values = c(.5,1))

  • Related