参数意味着不同的行数与绘制数据帧行

时间:2015-09-17 12:32:36

标签: r ggplot2 dataframe

我的数据框df看起来像这样

        a    b     c     d
row1    1    2     2     3
row2    2    4     5     9
row3    1    4     4     6

对于每一行,我想将直方图写入pdf中的页面。我试着这样做

for (i in 1:nrow(df)){
    histogram <- ggplot(data=df, aes(x=as.numeric(df[i,]))) +geom_histogram()
    ggsave(filename="output.pdf", plot=histogram)
}

然而,这给了我错误arguments imply differing number of rows: 115, 734。从这个回答:https://stackoverflow.com/a/26148043/651779我试图做

df$id <- rownames(df)
df <- melt(df)
for (i in 1:nrow(df)){
  histogram <- ggplot(data=df, aes(x=as.numeric(df[i,]))) +geom_histogram()
  ggsave(filename="output.pdf", plot=histogram)
}

但这给了我同样的错误,但数字arguments imply differing number of rows: 3, 84410

不同

2 个答案:

答案 0 :(得分:2)

怎么样:

for (i in 1:nrow(df)) {
  df2 <- data.frame(x = as.numeric(df[i, ]))
  histogram <- ggplot(data = df2, aes(x)) + geom_histogram()
  ggsave(filename = "output.pdf", plot = histogram)
}

答案 1 :(得分:2)

我会使用t转置data.frame,然后绘制如下:

#transpose df
df <- data.frame(t(df))

#notice aes_string in order for i to be the name as character
for (i in names(df)){
  histogram <- ggplot(df, aes_string(x=i)) + geom_histogram()
  ggsave(filename="output.pdf", plot=histogram)
}