【问题标题】:naming plots using ggplot, that are being looped by lapply使用 ggplot 命名图,由 lapply 循环
【发布时间】:2012-08-16 21:21:06
【问题描述】:

我正在使用lapply创建一个地块列表(ggplot2

假设我有这个功能

plot <- function(x){
  ggplot(x,aes(x=timepoints,means)) + 
       geom_point() + 
       geom_line() +
       scale_x_continuous(name='some name') +
       scale_y_continuous(name='another name') +
       geom_errorbar(aes(ymin=means-stderrs,ymax=means+stderrs),width=2) + 
       opts(title = names(x))    
}                 

我将通过一个数据框列表循环它,这里是列表中两个数据框的示例:

$name1

   means    stderrs        timepoints
1  603.784863 289.952382       0
2  120.00     99.000           20
$name2
   means   stderrs
1  17.425819  5.204339         0
2  25.9       8.0              20

我的问题: 我的 ggplot 函数的 names(x) 部分将每个图命名为“意思”,而不是该数据框的实际名称(例如 name1,name2) 该函数位于list[[i]] 中,我想要该实际数据框的名称,即names(list[i])

问题: 可以这么说,有没有办法引用列表中的外层?还是有更简单的方法来获取这些地块及其各自名称的列表?

【问题讨论】:

  • 你很少需要在ggplot 中使用这个结构。你能用一个完整的例子来扩展你的问题,包括你要子集的初始列表吗?
  • 看起来您要绘制一个具有未定义x 坐标timepoints 的单点。您始终可以将另一个项目添加到包含该名称的列表中。但最短的答案是否定的,lapply 只查看列表元素内的数据,不知道外部列表或其名称。或者使用lapply(seq_along(yourlist), ...) 并按照您描述的方式进行索引。
  • 这是可行的。它需要对您的代码思想进行一些更改

标签: r ggplot2


【解决方案1】:

它不漂亮,但它有效。

plot2 <- function(x, title){
  ggplot(x,aes(x=timepoints,means)) + 
      geom_point() + 
      geom_line() +
      scale_x_continuous(name='some name') +
      scale_y_continuous(name='another name') +
      geom_errorbar(aes(ymin=means-stderrs,ymax=means+stderrs),width=2) + 
      opts(title = title)
}

lapply(names(your_list), function(x) plot2(your_list[[x]], x))

【讨论】:

    猜你喜欢
    • 2019-06-21
    • 2022-01-11
    • 2021-07-31
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多