Home > Enterprise >  Using ggplot to make a bar graph showing sums of columns, separated by all column labels, and fill e
Using ggplot to make a bar graph showing sums of columns, separated by all column labels, and fill e

Time:09-07

I am wanting to make a bar graph that shows counts of the totals of each column, separated by column name (each bar is for X1, X2,X3....), stacked with a fill by row name (group1:group6). The problem is that I cannot figure out the aesthetic argument in the ggplot call. Here is some sample code

set.seed(1)
example_matrix <-matrix(rpois(90,7), nrow=6,ncol=15)
example_df <- data.frame(example_matrix)
rownames(example_df) <-c('group1','group2','group3','group4','group5','group6')
example_df ```

CodePudding user response:

Seems like you need might like to reshape the data from a wide format to a long format, which is much easier to ggplot with.

library(ggplot2)
library(tidyr)

set.seed(1)
example_matrix <-matrix(rpois(90,7), nrow=6,ncol=15)
example_df <- data.frame(example_matrix)
rownames(example_df) <-c('group1','group2','group3','group4','group5','group6')

df <- reshape2::melt(as.matrix(example_df))

ggplot(df, aes(Var2, value, fill = Var1))  
  geom_col()

Created on 2022-08-30 by the reprex package (v2.0.1)

  • Related