Home > Blockchain >  Proportional Bar Chart from Dataframe Created from Melt of Another Data Set
Proportional Bar Chart from Dataframe Created from Melt of Another Data Set

Time:09-08

I need to create a proportional bar chart from a data set created by using the melt function from dplyr. By proportional, I mean that I would need a chart for which the height of each bar would be different, based on the proportion of the total. I would like to proportion to be for the value X generated by the following sample code, with fill based on "group". I have tried many online solutions, and I constantly run into not an error code, but solid bars, with no difference in proportions

See sample code:

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

CodePudding user response:

library(data.table)
library(ggplot2)

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))
df$fraction <- df$value/sum(df$value)

setDT(df)

p <-
  ggplot(data = df, aes(x = Var2, y = fraction, fill = Var1))  
  geom_bar(stat = "identity")  
  scale_fill_manual(values = c("blue", "red", "black", "orange", "pink", "yellow"))

print(p)

CodePudding user response:

I don't think this can be done with the plotting commands directly, you'll need to transform your data before. For example:

library(dplyr)
df <- df %>% group_by(Var2) %>% mutate(fraction = value/sum(value))

and then plot either with the ggplot solution from the other answer or here's a plotly version:

library(plotly)
plot_ly(data = df, x = ~Var2, y = ~fraction, color = ~Var1, type = 'bar')
  • Related