0
library(ggplot2)
library(reshape)
df1<-data.frame(id=c("a","b","c","d"),
                var1=c(2,4,4,5),
                var2=c(5,6,2,6),
                var3=c(5,3,2,1))
df1.m <- melt(df1,id.vars = "id") 
ggplot(df1.m, aes(x = id, y = value,fill=variable)) +
  geom_bar(stat='identity')+coord_flip()

#edited attempt
my.func<-function(x){
  xx<-melt(x, id.vars="id")
  ggplot(xx, aes(x = id, y = value,fill=variable)) +
    geom_bar(stat='identity')+coord_flip()
}
results<-apply(df1, 1,my.func)

I have the above dataframe. I would like a function to create a stacked barchart for each id seperately, so that ultimately I would have 4 stacked barcharts: one for a, b, c, and d respectively. I'm confused as to how to do this. Thanks edit: the 4 barcharts would ultimately be graphed separately in their own window. So I know there is at least a user defined function involved. Or at least I think I know.

  • Does [a discussion here](https://stackoverflow.com/questions/12715635/ggplot2-bar-plot-with-both-stack-and-dodge) not answer your question? – Ekatef Apr 05 '18 at 10:18
  • Possible duplicate of [stacked bar plot with ggplot](https://stackoverflow.com/questions/22189435/stacked-bar-plot-with-ggplot) – Michael Harper Apr 05 '18 at 11:11
  • I should clarify that I would ultimately like 4 barcharts separately; as if i I had made a graph for a, then for b, then c, then d. I know this requires a user defined function to be created. Or at least I think it does, but I can not make sense of it yet given my knowledge of R. – JoeyMcDougalhauser Apr 05 '18 at 21:24

1 Answers1

1

You are almost there. Fill by variable

  ggplot(df1.m, aes(x=id, y=value, fill=variable)) + 
  geom_bar(stat="identity") +coord_flip()

enter image description here

Use facet_wrap()

 ggplot(df1.m, aes(x=id, y=value, fill=variable)) + 
      geom_bar(stat="identity") + facet_wrap(~id)
ReKx
  • 996
  • 2
  • 10
  • 23