【问题标题】:Plot columns from list of data frames从数据框列表中绘制列
【发布时间】:2014-11-10 15:43:51
【问题描述】:

我正在尝试将一些日期划分为季节,然后结合每个季节的“日期和振幅”月度图。

head(dat)
    Date  Amplitude
1 2009-09-13 -2.6966667
2 2009-09-14 -0.7264583
3 2009-09-15 -2.1823333

这是我为情节标题创建季​​节和 YearMonth 的代码:

x <- as.Date(dat$Date, format="%Y/%m/%d")
x <- as.Date(x, origin="2009-09-13")
x <- cut(x, breaks="quarter")
labs <- paste(substr(levels(x),1,4),"/",1:4, sep="")
dat$DateQ <- factor(x, labels=labs)
dat$YearMonth <- format(dat$Date, "%Y/%m")
head(dat)
Date  Amplitude  DateQ YearMonth
1 2009-09-13 -2.6966667 2009/1   2009/09
2 2009-09-14 -0.7264583 2009/1   2009/09

我使用拆分为每个季节创建数据帧,然后用 for 循环命名数据帧

dat_split_season <- split(dat, dat$DateQ)
new_names <- c("Summer_2009", "Fall_2009", "Winter_2010", "Spring_2010", 
          "Summer_2010", "Fall_2010", "Winter_2011",
          "Spring_2011", "Summer_2011", "Fall_2011",
          "Winter_2012", "Spring_2012", "Summer_2012")
for (i in 1:length(dat_split_season)) {
assign(new_names[i], dat_split_season[[i]])
}

我可以通过更改 df 手动按季节创建所需的月度图

df <- Winter_2012
graphs <- lapply(split(df,df$YearMonth),
   function(gg) ggplot(gg, aes(x=Date, y=Amplitude)) +
     geom_point() + geom_line() + ylim(-10, 10) +
     ggtitle(paste(gg$YearMonth)) + theme_bw())
do.call("grid.arrange", graphs)

我想使用 for 循环或 apply() 系列对季节列表进行排序,为每个数据框选择 Date 和 Amplitude 列并按“YearMonth”绘制。

我遇到的问题可能与语法有关;我是 R 和一般编程的新手。但我最近几天一直在搜索论坛,在这一点上我会很感激一些方向。谢谢!

【问题讨论】:

  • 所以问题是您的ggplot 呼叫工作不正常?
  • ggplot 调用工作正常 - 我想沿数据帧列表排序,将每个季节传递给 ggplot 调用,而无需手动输入。即按季节拆分 dat,按 $YearMonth 拆分季节,传递给 ggplot。一体。这有意义吗?
  • 也许,所以你有一个数据框列表,每个数据框都是一个季节?您想要每个季节的图网格(每个面板是 YearMonth),还是想要每个 YearMonth 完全独立的图?
  • 我想要每个季节的地块网格(3 个地块),每个面板都是 YearMonth。当我手动传递一个季节(即 df = season)时,ggplot 调用实现了这一点,但我想循环从 split(dat, dat$DateQ) 到将 season$YearMonth 传递给 ggplot 的整个过程。

标签: r lapply


【解决方案1】:

这是一个最小的示例,我相信它可以重新创建您想要的输出

df1<-data.frame(YearMonth=c(rep('Aug_2012',10),rep('Sep_2012',10),rep('Oct_2012',10)), value=rnorm(30),t=rep(1:10,3) )
df2<-data.frame(YearMonth=c(rep('Aug_2012',10),rep('Sep_2012',10),rep('Oct_2012',10)), value=rnorm(30),t=rep(1:10,3) )
df_list<-list(df1,df2)

myplots<-lapply(df_list,function(x)
p<-ggplot(x,aes(x=t,y=value,group=factor(YearMonth),color=factor(YearMonth))) + geom_line() + facet_wrap(~YearMonth)
)

lapply 用于访问数据框列表,然后facet_wrap 用于为每个数据框创建绘图网格。

【讨论】:

  • 这行得通,谢谢!您能否快速解释一下为什么将 ggplot 函数分配给 lapply() 中的变量“p”
  • 您可以保存ggplot 对象,以便稍后决定打印它们或保存或添加图层。不过我们不必这样做 - 无论哪种方式,lapply() 的结果都将是一个 ggplot 对象列表,我将其命名为 myplots
猜你喜欢
  • 2018-08-01
  • 2021-12-27
  • 1970-01-01
  • 2017-07-02
  • 2020-01-02
  • 1970-01-01
  • 2021-11-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多