【问题标题】:arguments imply differing number of rows with plotting row of dataframe参数暗示不同的行数与绘制数据框的行
【发布时间】:2015-09-17 12:32:36
【问题描述】:

我有一个数据框 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

【问题讨论】:

    标签: r ggplot2 dataframe


    【解决方案1】:

    怎么样:

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

    【讨论】:

      【解决方案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)
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-02-13
        • 2015-12-08
        • 1970-01-01
        • 1970-01-01
        • 2021-01-01
        • 2018-07-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多