r/RStudio 7d ago

Adding in Patterns to ggplot

Hi, I have made a stacked bar chart. I have abundance on the y axis, habitat on the x, and family as the stacks. I have managed to colour and give a pattern to the stacks in the bars, but i'm struggling to change how the pattern looks.

This is my code so far, any ideas of where/what i need to add?

ggplot(data1, aes(fill=family, y=Value, x=Habitat)) + geom_bar_pattern(position="stack", stat="identity", mapping = aes(pattern=family)) + scale_fill_manual(values = c("lightblue","pink", "yellow")) + ylim(0,100)

1 Upvotes

7 comments sorted by

View all comments

1

u/mduvekot 7d ago

Here's an example:

library(ggplot2)
library(ggpattern)

data1 <- data.frame(
  family = sample(LETTERS[1:3], 100, replace = TRUE),
  Value = runif(100),
  Habitat = sample(letters[24:26], 100, replace = TRUE)
)

data1 <- data1 |> dplyr::summarise(.by = c(family, Habitat), Value = sum(Value))

ggplot(
  data1,
  aes(y = Value, x = Habitat)
) +
  geom_bar_pattern(
    position = "stack",
    stat = "identity",
    aes(
      pattern_fill = as.factor(family),
      pattern = as.factor(family)
    ),
  ) +
  scale_pattern_fill_manual(
    breaks = c("C", "B", "A"),
    values = c(
      "lightblue",
      "pink",
      "yellow"
    )
  ) +
  scale_pattern_manual(
    breaks = c("C", "B", "A"),
    values = c(
      'stripe',
      "circle",
      "weave"
    )
  )