Home > OS >  Reformat output of R table() command for plotting
Reformat output of R table() command for plotting

Time:06-02

I wish to plot some count data (likely as a bubble plot). I've some different experiments and for each experiments I've three replicates. The output from the table command is given below.

> with(myData.df, table(ChargeGroup,Expt,Repx))
, , Repx = 1

           Expt
ChargeGroup Ctrl CV2 Gas n15 n30 n45 n60 p15 p30  v0
    < 10     540 512 567 204 642 648  71   2   2   6
     10: 15  219 258 262 156 283  16   0   1   0   7
     15: 20  119 118  14 200  14   0   0   7   0  51
     20: 25   57  38   0  84   1   0   0  31   7  87
     25:      30  16   0  17   0   0   0  24  19  18

, , Repx = 2

           Expt
ChargeGroup Ctrl CV2 Gas n15 n30 n45 n60 p15 p30  v0
    < 10     529 522 582 201 642 626  77   1   2   5
     10: 15  232 249 264 150 273  14   0   1   0   5
     15: 20  116 113  18 204  13   0   0  12   0  41
     20: 25   53  46   0  82   0   0   0  36   6  94
     25:      28  12   0  26   0   0   0  33  21  28

, , Repx = 3

           Expt
ChargeGroup Ctrl CV2 Gas n15 n30 n45 n60 p15 p30  v0
    < 10     536 525 591 224 671 641  63   1   2   6
     10: 15  236 238 257 170 276  16   0   2   1  10
     15: 20  113 108  15 212  12   0   0  10   0  47
     20: 25   57  40   0  77   0   0   0  34   3 107
     25:      32  11   0  25   0   0   0  26  15  26

Can anyone help in to further process the output so that I can go directly for plotting in either base graphics or ggplot? Thanks

CodePudding user response:

There are couple of methods - with base R, by looping over the third dmension and plotting with barplot

par(mfrow = c(3, 1))
apply(with(myData.df, table(ChargeGroup,Expt,Repx)), 3, barplot)

-testing

par(mfrow = c(3, 1))
apply(with(mtcars, table(cyl, vs, gear)), 3, barplot)

Or convert to a single data.frame with as.data.frame and using ggplot or directly get the data.frame/tibble output with count

library(dplyr)
library(ggplot2)
myData.df %>%
   count(ChargeGroup,Expt,Repx) %>%
   ggplot(aes(x=ChargeGroup, y = n, fill = Expt))  
     geom_col()  
     facet_wrap(~ Repx)

-testing

mtcars %>%
   count(cyl = factor(cyl), vs = factor(vs), gear = factor(gear)) %>% 
   ggplot(aes(x = cyl, y = n, fill = vs))  
    geom_col()   
    facet_wrap(~ gear)
  • Related