rggplot2ggpattern

Is there a way to add stripes to bar graphs in ggplot2?


I have six sites that I want to make into bar graphs, with site name on the x-axis and rates (numbers) on my y-axis. My sites are Site 1, Site 1 Hardwood, Site 2, Site 2 Hardwood, Site 3, Site 3 Hardwood. I would like the bars for the Hardwood sites to be the same color as their corresponding Sites, but have stripes. I can create the bar graph itself, but adding stripes has been more of a hassle.

#Site set up
sites <- c("Mt. Grace", "Mt. Grace Hardwood", "White's Pond", "White's Pond Hardwood", "TriMountain", "TriMountain Hardwood")
nitr_rates <- c(-0.90855, -0.7161, -0.46017, -0.30943, -0.21913, 0.2995)
striped_sites <- c("Mt. Grace Hardwood", "White's Pond Hardwood", "TriMountain Hardwood") #Make these striped
Color <- c("#5BA300", "#5BA300", "#0073E6", "#0073E6", "#B51963", "#B51963")
Stripe <- ifelse(sites %in% striped_sites, "stripe", NA)
Nitri_data <- data.frame(sites, nitr_rates, Color, Stripe)
site_order <- c("Mt. Grace", "Mt. Grace Hardwood", "White's Pond", "White's Pond Hardwood", "TriMountain", "TriMountain Hardwood")

#Graph
ggplot(Nitri_data, aes(x = factor(sites, levels = site_order), y = nitr_rates, fill = Color)) +
  geom_bar(stat = "identity", color = "black", alpha = 0.7, aes(pattern = Stripe)) +
  scale_pattern_manual(values = c("stripe" = "stripe")) +
  scale_fill_manual(values = c("#5BA300", "#0073E6", "#B51963" ), guide = guide_legend(override.aes = list(fill = c("#5BA300", "#0073E6", "#B51963")))) +
  xlab("Site") +
  ylab("mg N/g dry wt. soil/28 days") +
  ggtitle("Net Nitrification") +
  theme_minimal() +
  theme(legend.position = "bottom")

This code creates a bar graph with my site sites, but does not include striping.


Solution

  • To get a pattern you have to use geom_col_pattern. Also, to make this work assign a non-NA value to Stripe for cases where you don't want a pattern, e.g. I have chosen "none". Finally, doing so you could use scale_pattern_identity to apply the patterns.

    library(ggplot2)
    library(ggpattern)
    
    Nitri_data$Stripe <- ifelse(Nitri_data$sites %in% striped_sites, "stripe", "none")
    
    ggplot(Nitri_data, aes(x = factor(sites, levels = site_order), y = nitr_rates, fill = Color)) +
      geom_col_pattern(color = "black", alpha = 0.7, aes(pattern = Stripe)) +
      scale_pattern_identity() +
      scale_fill_manual(
        values = c("#5BA300", "#0073E6", "#B51963")
      ) +
      xlab("Site") +
      ylab("mg N/g dry wt. soil/28 days") +
      ggtitle("Net Nitrification") +
      theme_minimal() +
      theme(legend.position = "bottom")
    

    enter image description here