0

I have a dataframe with 4 columns. Three are the concentrations of heavy metals in whales with two different feeding modes. Is it possible to have a grouped barchart with concentration (ug/g) on the y axis then three different groups for the element concentrations on the x axis with each one comparing 'filter' and 'raptorial' feeders.

I tried using

    factors = c(Filter, Raptorial), 
    dataframe = bothfmnewdata, 
    errbar = FALSE, 
    ylim=c(0, 140)) '''



|Feeding mode| Hg | Se | Cu |
|------------|----|----|----|
|Filter      |0.28|0.47|0.89|
|Raptorial   |0.67|1.09|0.08|
|Raptorial   |2.45|5.90|2.22|
|Filter      |4.20|0.01|3.45|
|Filter      |0.20|3.45|1.34|
|Raptorial   |4.55|6.13|3.33|

Output of dput():

dput(bardataframe) structure(list(fm = c("Raptorial", "Raptorial", "Raptorial", "Raptorial", "Filter", "Raptorial", "Raptorial", "Raptorial", "Filter", "Raptorial", "Raptorial", "Filter", "Filter", "Filter", "Filter", "Filter", "Raptorial", "Raptorial", "Filter", "Filter" ), hg = c(3.1738, 10.5, 18.31, 3.078, 0.09958, 1.67, 0.37, 4.1, 0.00135, 1.779, 0.05, 0.0065, 0.045, 0.029, 0.003, 0.012, NA, 1.29, 0.06, 0.058), cu = c(NA, NA, NA, NA, 0.23, NA, NA, NA, 2.635, NA, 8.1, NA, 3.03, 0.92, 0.6, 0.6, 0.24, NA, 0.285, 5.47 ), se = c(NA, NA, NA, NA, 0.76, NA, NA, 0.697, NA, NA, 0.35, 0.255, 1.13, 0.016, 0.105, 0.149, NA, NA, 0.132, NA)), row.names = c(43L, 45L, 46L, 50L, 64L, 70L, 72L, 73L, 74L, 75L, 90L, 97L, 98L, 99L, 100L, 101L, 106L, 122L, 151L, 152L), class = "data.frame")

poxyatr
  • 11
  • 1
  • Could you copy us the output of dput() on your data? It will be easier to help out with sample code. – jpenzer Apr 17 '22 at 19:18

1 Answers1

1

The simplest way to plot this is to transpose your data into long format; that is, have all the values in a single column, with a separate column labelling the values according to the element they represent. This can be done with tidyr::pivot_longer. Then we can get the mean value for each combination of element and feeding mode using group_by and summarise from dplyr. Finally we can pass the modified data frame to ggplot to get a fully customizable bar plot.

All of these functions are available within the tidyverse suite of packages.

library(tidyverse)

bardataframe %>% 
  rename(Hg = hg, Cu = cu, Se = se) %>%
  pivot_longer(-1, names_to = "Element", values_to = "Concentration") %>%
  group_by(Element, fm) %>%
  summarise(Concentration = mean(Concentration, na.rm = TRUE)) %>%
  ggplot(aes(Element, Concentration, fill = fm)) +
  geom_col(position = position_dodge(width = 0.8), width = 0.6) +
  theme_light() +
  scale_fill_brewer(palette = "Set1", name = "Feeding mode") +
  theme(text = element_text(size = 16)) +
  labs(y = expression(Concentration~(mu*g / l)))

enter image description here

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87