-2

I have the data frame below. I now want grouped barplots with 4 variables grouped per SU. And this for all the SU's.

> dat
   SU AGC.low AGC.high SOC.low SOC.high
1   1   22.12    24.04  176.34   208.85
2   2   10.14    11.02  225.49   269.30
3   3   18.23    19.82  122.80   239.54
4   4   36.14    39.28  163.45   164.98
5   5   47.56    51.69  127.79   174.26
6   6   38.98    42.37  218.30   351.22
7   7   47.74    51.89  199.52   215.23
8   8   15.17    16.49  136.26   141.18
9  10   30.24    32.87  220.81   254.27
10 11   33.28    36.17  459.77   620.63
11 15   40.27    43.78  229.19   231.03```

1 Answers1

1

One option is to pivot to long format with pivot_longer and plot with ggplot

library(dplyr)
library(tidyr)
library(ggplot2)
dat %>%       
   pivot_longer(cols = -SU) %>%
   ggplot(aes(x = name, y = value, fill = SU)) + 
          geom_col()

Or it could be

dat %>% 
    pivot_longer(cols = -SU) %>% 
    ggplot(aes(x = SU, y = value, fill = name)) +
       geom_col()

Or in base R with barplot

barplot(`row.names<-`(as.matrix(dat[-1]), dat$SU), legend = TRUE)

data

dat <- structure(list(SU = c("1", "2", "3", "4", "5", "6", "7", "8", 
"10", "11", "15"), AGC.low = c(22.12, 10.14, 18.23, 36.14, 47.56, 
38.98, 47.74, 15.17, 30.24, 33.28, 40.27), AGC.high = c(24.04, 
11.02, 19.82, 39.28, 51.69, 42.37, 51.89, 16.49, 32.87, 36.17, 
43.78), SOC.low = c(176.34, 225.49, 122.8, 163.45, 127.79, 218.3, 
199.52, 136.26, 220.81, 459.77, 229.19), SOC.high = c(208.85, 
269.3, 239.54, 164.98, 174.26, 351.22, 215.23, 141.18, 254.27, 
620.63, 231.03)), row.names = c("1", "2", "3", "4", "5", "6", 
"7", "8", "9", "10", "11"), class = "data.frame")
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Your code provides stacked bar plots, instead of grouped bar plots. These are also ordered by variable and not SU. Which is the output I'm looking for. – user13608970 Jul 15 '20 at 21:31
  • @user13608970 If you meant to get the transposed barplot, use `barplot(t(`row.names<-`(as.matrix(dat[-1]), dat$SU)), legend = TRUE)` – akrun Jul 15 '20 at 21:32