Home > Net >  Making a unique grouped bar graph for multiple different data frames
Making a unique grouped bar graph for multiple different data frames

Time:11-10

I have a series of about 300 data frames each structured the same way and want to write a code that will turn each of them into their own bar graph. I am struggling to write a code that structures the graph correctly in the first place. My data frames look like this as an example:

precursorMz Mz_Round HW Intensity Reg Intensity diff1 diff2
1    256.6814   141.10         4216          3994  0.96  1.00
2    256.6814   142.10         7184          5988  1.00  1.02
3    256.6814   143.12        44510         30020  1.02  1.00
4    256.6814   144.12         1858          1312  1.00  0.00
5    256.6814   260.20        43010         23230  4.52  1.00
6    256.6814   261.20         9452          6388  1.00  0.99

I want my graph to have the Mz_Round column be the X axis and then my Y values be HW Intensity and Reg Intensity.

I have tried using the barplot() function but again am having issues with getting my axes to be correct.

intensities <- table(split1$`HW Intensity`, split1$`Reg Intensity`)
barplot(intensities,
        main = "Intensity Compared",
        xlab = "M/z", ylab = "Intensity",
        col = c("darkgrey", "blue"),
        rownames(split1$Mz_Round),
        beside = TRUE)

CodePudding user response:

I have tried a couple of plots. I hope this helps.

# Data
> dput(df)
structure(list(precursor_Mz = c(256.6814, 256.6814, 256.6814, 
256.6814, 256.6814, 256.6814), Mz_Round = c(141.1, 142.1, 143.12, 
144.12, 260.2, 261.2), HW_Intensity = c(4216, 7184, 44510, 1858, 
43010, 9452), Reg_Intensity = c(3994, 5988, 30020, 1312, 23230, 
6388), diff1 = c(0.96, 1, 1.02, 1, 4.52, 1), diff2 = c(1, 1.02, 
1, 0, 1, 0.99)), class = c("spec_tbl_df", "tbl_df", "tbl", "data.frame"
), row.names = c(NA, -6L), spec = structure(list(cols = list(
    precursor_Mz = structure(list(), class = c("collector_double", 
    "collector")), Mz_Round = structure(list(), class = c("collector_double", 
    "collector")), HW_Intensity = structure(list(), class = c("collector_double", 
    "collector")), Reg_Intensity = structure(list(), class = c("collector_double", 
    "collector")), diff1 = structure(list(), class = c("collector_double", 
    "collector")), diff2 = structure(list(), class = c("collector_double", 
    "collector"))), default = structure(list(), class = c("collector_guess", 
"collector")), skip = 1L), class = "col_spec"))

library(tidyverse)

# pivoting data
df1 <- df|>
  select("Mz_Round", "HW_Intensity", "Reg_Intensity")|>
  pivot_longer(!Mz_Round)

# stacked bar plot
ggplot(df1)  
  geom_col(aes(x = as.factor(Mz_Round), y = value, fill = name))

# dodged bar plot
ggplot(df1)  
  geom_col(aes(x = as.factor(Mz_Round), y = value, fill = name), position = "dodge")

enter image description here enter image description here

  • Related