0

I want to plot 3 different mean values (Mean1, Mean2 and Mean3) for 4 different species (A, B, C and D). I have 1 mean value per species and per years (2005, 2013 and 2022). Here is my R code (doesn't work):

ggplot(df, aes(x = interaction (Species, Year), y = c(Mean1, Mean2, Mean3, Mean4), fill = c(Mean1, Mean2, Mean3, Mean4)) + geom_bar(position = "stack", stat="identity")

I am trying to make the same type of barplot as shown on the picture on R but I don't manage to have all the mean (Mean1, Mean2, Mean3) on the same plot because they all come from a different column of my dataframe (see table on the image).

enter image description here

Is it possible to have more than one "fill" variable ? Or something else to obtain the same plot ?

stefan
  • 90,330
  • 6
  • 25
  • 51
  • 2
    Welcome to SO! That's not the way ggplot2 works. For your case you have to reshape your data to long or tidy format, e.g. try `df %>% tidyr::pivot_longer(c(Mean1, Mean2, Mean3, Mean4), names_to = "name", values_to = "value") %>% ggplot(aes(x = interaction (Species, Year), y = value, fill = name) + geom_bar(position = "stack", stat="identity")`. If you need more help then you should provide [a minimal reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) including a snippet of your data or some fake data. – stefan Nov 02 '22 at 11:18
  • You've identified your main issue: your data frame is not [tidy](https://cran.r-project.org/web/packages/tidyr/vignettes/tidy-data.html). `ggplot2` (and the rest of the tidyverse) is designed to work with tidy data. Make your data tidy by using `pivot_longer`. This will give you a data frame with columns (say) `Mean`, `Species`, `Year` and `Value`. and your life will become much easier. – Limey Nov 02 '22 at 11:18
  • The *reason* your data frame is not tidy is that you have information you need to plot (Year and Species) in the *names* of your columns rather than in the *values* they contain. – Limey Nov 02 '22 at 11:20
  • Thanks a lot, I understand yet how it works and how I need to prepare my data ! – Céline G Nov 02 '22 at 11:53

0 Answers0