【问题标题】:Loop through multiple columns and make a plot for each in R?循环遍历多个列并在 R 中为每个列绘制一个图?
【发布时间】:2019-06-07 01:30:59
【问题描述】:

我有一个数据集,其中第一列是“年份”,接下来的 50 列是美国每个州的数据。我想在一个 pdf 中生成多个图,将每个“状态”列与“年份”列(即 [,1] 和 [,2]、[,1] 和 [,3]、... [,1]和 [,50]。

我认为循环遍历第 2-50 列会是一个很好的解决方案,但我无法让它在 plot 函数中工作。我是循环的新手,所以我不确定如何继续。以下是我的数据集中的一个示例以及我遇到问题的部分代码

testUS:
Year    ME   NH    VT   MA   RI   CT    NY
1953    4017 1579 5057 12215 1582 9252  23507
1954    5265 1351 1733 18561 633  8402  21002
1955    740  788  2214 9719  787  3958  22317
1956    985  184  1537 6458  957  5575  26639

pdf("testUSgraph.pdf")
for (i in 2:50) {
  plot(testUS[,1], testUS[,i])
}
dev.off

我收到的错误消息:

function (which = dev.cur()) 
{
    if (which == 1) 
        stop("cannot shut down device 1 (the null device)")
    .External(C_devoff, as.integer(which))
    dev.cur()
}
<bytecode: 0x1075edc30>
<environment: namespace:grDevices>

此外,每当我将 testUS[,i] 分配给变量时,该变量只会调用一种状态的数据(即仅显示第 50 列的数据)。

【问题讨论】:

    标签: r


    【解决方案1】:

    假设您的数据框是df

    library(ggplot2)
    
    col_names <- colnames(df)
    col_names <- col_names[-1]
    
    for (i in col_names){
        plot <- ggplot(df, aes_string(x=df$Year, y=i)) +
        geom_point()
        print(plot)
    }
    

    这应该将它们作为单独的图返回。

    编辑:在同一视图中返回绘图,并保存为 pdf,

    col_names <- colnames(df)
    col_names <- col_names[-1]
    
    plot_list <- list()
    
    for (i in col_names){
        plot <- ggplot(df, aes_string(x=df$Year, y=i)) +
        geom_point()
        plot_list[[i]] <- plot
    }
    plot_grob <- arrangeGrob(grobs=plot_list)
    pdf("testUSgraph.pdf")
    grid.arrange(plot_grob)
    dev.off()
    

    (在初始代码中保存 pdf 的问题可能是因为您忘记了括号,dev.off 应该是 dev.off()

    【讨论】:

    • 同样的问题,只绘制第 50 列。当我尝试 pdf/dev.off 时,我收到与上面相同的错误消息。
    • 为了清楚起见,你不能按情节部分的左箭头循环到以前的情节吗?肯定只返回一个情节?
    • ope,是的,抱歉,这是正确的。谢谢...是否可以将其与每个图表合并为pdf?当我尝试这样做时,仍然会给出错误消息。
    • 不用担心。检查我的编辑以制作组合图。如果 pdf 代码不起作用,您应该可以单击 Export --> 另存为 PDF。
    • 您好!我可以在我的脚本中使用您的代码,但是,我需要绘制饼图,而不是通过 col_names 循环的点。我试图创建百分比。你帮我修复这个代码plot_list &lt;- list() for (i in col){ plot &lt;- ggplot(ds_original_t1, aes_string(x=1, y=i)) + geom_bar( stat = "identity", fill = "lightblue", colour = "black") plot_list[[i]] &lt;- plot }
    猜你喜欢
    • 2021-11-06
    • 2018-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-16
    • 2015-12-11
    • 2014-08-17
    相关资源
    最近更新 更多