简体   繁体   中英

Using ggplot to make a bar graph showing sums of columns, separated by all column labels, and fill equal to all row labels

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 ```

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM