R:为数据框中的每一行创建suplots

时间:2016-02-19 21:55:01

标签: r dataframe bar-chart subplot

我有以下数据框:

V1 V2 V3 V4 V5
A  0  3  1  0
R  4  2  0  0
Q  0  2  4  0

V1是标识符,剩余列类似于实际数据。

我想为此数据框中的每一行创建条形图。我尝试使用melt重塑为长格式并将问题矢量化但不成功。有没有办法不需要编写函数?

编辑: 这是我最后想看到的(只是原理布局):

https://plot.ly/~MattSundquist/11035.png

3 个答案:

答案 0 :(得分:2)

这样做怎么办?

library(tidyr)
library(dplyr)

df_n <- gather(df, key = V1)
names(df_n) <- letters[1:3]
ggplot(df_n, aes(a, c, fill=b)) + geom_bar(position="dodge", stat="identity")

enter image description here

EDITED版本:

使用刻面:

ggplot(df_n, aes(a, c, fill=b)) + geom_bar(position="dodge", stat="identity") + facet_grid(.~a, scales = "free")

enter image description here

答案 1 :(得分:0)

这就是你想要的:

d<-data.frame(V1=c('A','R','Q'),V2=c(0,4,0),
               V3=c(3,2,2),V4=c(1,0,4),V5=c(0,0,0))
rownames(d)<-d[,1]
barplot(t(as.matrix(d[,-1])),beside=T) # barplots for group A, R, Q.

答案 2 :(得分:0)

我只做了一个专栏,但是我想到了这个想法:

df = data.frame(v1 = c('A', 'R', 'Q'), v2 = c(0,4,0))
dat1 = split(df, df$v1)
str(dat1)
lapply(dat1, FUN=function(x) ggplot(data=x, aes(v1, v2)) + geom_bar(stat="identity"))