Home > Net >  Plot multiple variables on same Barplot in R
Plot multiple variables on same Barplot in R

Time:09-30

I would really appreciate some help with this plot. I'm very new to R and struggling (after looking at many tutorials!)to understand how to plot the following:

This is my Table Stacked barplot of OP's data

CodePudding user response:

Thanks everyone for your help. I was able to make the plot as follows:

First, I made a new table from data I imported into R:

#Make new table of patientID and tot cell count
patientID <- c("a", "b", "c")
tot_cells <- c(tot_cells_a, tot_cells_b, tot_cells_c)
tot_cells_zone1 <- c(tot_cells_a_zone1, tot_cells_b_zone1, tot_cells_c_zone1)
tot_cells_zone2 <- c(tot_cells_a_zone2, tot_cells_b_zone2, tot_cells_c_zone2)
tot_cells_zone3 <- c(tot_cells_a_zone3, tot_cells_b_zone3, tot_cells_c_zone3)
tot_cells_table <- data.frame(tot_cells, 
                          tot_cells_zone1, 
                          tot_cells_zone2, 
                          tot_cells_zone3)
rownames(tot_cells_table) <- c(patientID)

Then I plotted as such, first converting the data.frame to matrix :

#Plot "Total Microglia Counts per Patient"

tot_cells_matrix <- data.matrix(tot_cells_table, rownames.force = patientID)

par(mar = c(5, 4, 4, 10), 
xpd = TRUE)

barplot(t(tot_cells_table[1:3, 1:4]), 
    col = c("red", "blue", "green", "magenta"),
    main = "Total Microglia Counts per Patient", 
    xlab = "Patient ID", ylab = "Cell #",
    beside = TRUE)

legend("topright", inset = c(- 0.4, 0),
   legend = c("tot_cells", "tot_cells_zone1", 
              "tot_cells_zone2", "tot_cells_zone3"), 
   fill = c("red", "blue", "green", "magenta"))

And the graph looks like this: Barplot of multiple variables

Thanks again for pointing me in the right direction!

  • Related