使用ggplot为数据框中的每一行创建堆叠条形图的功能

问题描述 投票:0回答:1
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)

我有上面的数据帧。我想要一个函数来为每个id单独创建一个堆叠的条形图,这样我最终会有4个堆叠的条形图:分别用于a,b,c和d。我很困惑如何做到这一点。谢谢编辑:4个条形图最终将在他们自己的窗口中单独绘制。所以我知道至少涉及一个用户定义的功能。或者至少我想我知道。

r ggplot2
1个回答
1
投票

你快到了。按变量填写

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

enter image description here

使用facet_wrap()

 ggplot(df1.m, aes(x=id, y=value, fill=variable)) + 
      geom_bar(stat="identity") + facet_wrap(~id)
© www.soinside.com 2019 - 2024. All rights reserved.