Chris Kouts
Chris Kouts

Reputation: 91

Grouped Barplot in ggplot2 in R with 2D Data Frame

Given df with labelled column and row names,

      A   B
ANM  16  26
ANO  35  28
PRI   4  14
WHP   0   4
STY 127 474
SUN  30   3
BLD 153  29
TBS   1  96
UCH   1  12
SKA   0   3
IRF   1   3
DOV  28   2

I wish to make the below plot using ggplot2. (I've made the below plot in base R but am aware ggplot2 is the superior) grouped double bar plot base R

I can, of course, replicate the column and row names into the form noted in documentation here or is there a way to express this directly with the aes() function given my data frame?

Upvotes: 0

Views: 50

Answers (1)

r2evans
r2evans

Reputation: 160447

library(dplyr)
# library(tidyr) # pivot_longer
library(ggplot2)
tibble::rownames_to_column(quux) %>%
  tidyr::pivot_longer(-rowname) %>%
  ggplot(aes(rowname, value, fill = name)) +
  geom_col(width = 0.5, position = position_dodge(width = 0.5)) +   
  theme_bw() +
  theme(panel.grid = element_blank())

basic ggplot barplot

Upvotes: 1

Related Questions