0

I am trying to create a bar chart that has the number of each species grouped into years. I want each year represented on the x axis with the number of each of the 3 species grouped next to one another under each year.

I am working with the following dataset which contains year, species, and the number of species counted for that year.

structure(list(year = c(2018L, 2018L, 2018L, 2019L, 2019L, 2019L, 
2020L, 2020L, 2020L, 2021L, 2021L, 2021L, 2022L, 2022L, 2022L, 
2023L, 2023L, 2023L), species = c(1L, 2L, 3L, 1L, 2L, 3L, 1L, 
2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L), n = c(96L, 15L, 
126L, 84L, 8L, 109L, 87L, 20L, 71L, 116L, 13L, 157L, 108L, 10L, 
112L, 129L, 11L, 186L)), class = c("grouped_df", "tbl_df", "tbl", 
"data.frame"), row.names = c(NA, -18L), groups = structure(list(
    year = c(2018L, 2018L, 2018L, 2019L, 2019L, 2019L, 2020L, 
    2020L, 2020L, 2021L, 2021L, 2021L, 2022L, 2022L, 2022L, 2023L, 
    2023L, 2023L), species = c(1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 
    3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L), .rows = structure(list(
        1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 
        14L, 15L, 16L, 17L, 18L), ptype = integer(0), class = c("vctrs_list_of", 
    "vctrs_vctr", "list"))), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -18L), .drop = TRUE))

I tried the following however it produced a stacked bar chart instead of a grouped one. Also, for some reason the legend has species in a gradual shade rather than 3 distinct species.

barplot <- df2 %>% 
  ggplot(
    aes(x = year, y = n, fill = species))+
  geom_col(position = "dodge", width = 0.5, alpha = 0.5, color = "black", linewidth = 0.1)
plot(barplot)
New contributor
Anna is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.

1 Answer 1

0

As the variable mapped on fill is a numeric aka continuous variable you have to convert to a discrete or categorical variable using e.g. factor or explicitly map on the group aes:

library(ggplot2)

df2 |> 
  ggplot(
    aes(x = year, y = n, fill = factor(species))
  ) +
  geom_col(
    position = "dodge", width = 0.5, alpha = 0.5,
    color = "black", linewidth = 0.1
  )


df2 |> 
  ggplot(
    aes(x = year, y = n, fill = species, group = species)
  ) +
  geom_col(
    position = "dodge", width = 0.5, alpha = 0.5,
    color = "black", linewidth = 0.1
  )

1
  • 1
    Ahh! Thank you so much.
    – Anna
    Commented 11 mins ago

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.