如何将 300 个月分成 60 组,以便 r 中的 ggplot2 x 轴可读性

How to split 300 months into groups of 60 for ggplot2 x-axis readability in r

我已经搜索了 2 或 3 天,试图找到解决我问题的方法,但没有成功。如果这真的很容易或已经存在,我深表歉意,但我找不到。我有 3 个数据框,长度从 1 到 300 不等。只能在 ggplot x 轴上显示大约 60 个值而不会变得不可读,我不想省略值,所以我试图找到一种计算每个数据帧的长度并将其拆分为 "x" 个图的方法,每个图不超过 60 个。

到目前为止我已经尝试过:facet_grid、facet_wrap、变换和拆分。 "Split" 可以很好地分割数据,但它会在变量名称的前面添加一个 "X1." "X2." ... "Xn." (其中 n 是它的分区数将数据分解成)。所以当我调用 ggplot2 时,它找不到我原来的变量名("Cost" 和 "Month"),因为它们看起来像 X1.Cost X1.Month、X2.Cost 等。 ..我该如何解决?

我乐于接受任何建议,尤其是如果我可以解决这两个问题(不是一次硬编码到 60 行并且分解成具有较小 x 轴范围的图表)。在此先感谢您的耐心等待和帮助。

斯蒂芬妮(绝望的研究生)

这是一些存根代码:

```{r setup, include=FALSE}
xsz <- 60 # would like not to have to hardcode this
ix1 <- seq(1:102) # would like to break into 2 or 3 approx equal graphs #
fcost <- sample(0:200, 102)
f.df <- data.frame("Cost" = fcost, "Month" = ix1)
fn <- nrow(f.df)
fr  <- rep(1:ceiling(fn/xsz),each=xsz)[1:fn]
fd <- split(f.df,fr)
fc <- numeric(length(fd))
for (i in 1:length(fd)){
  print(ggplot(as.data.frame(fd[i]), aes(Month, Cost)) +
    geom_line(colour = "darkred", size = .5) +
    geom_point(colour = "red", size = 1) +
    labs(x = "Projected Future Costs (monthly)", y = "Dollars") +
    theme_bw() +
    theme(plot.title = element_text(hjust = 0.5)) +
    theme(axis.text.x = element_text(angle = 60, vjust = .6))) 
}
```

当我 运行 它时,我得到: eval(expr, envir, enclos) 错误:未找到对象 'Month'

当我这样做时: 姓名(as.data.frame(fd[1]))

我得到: [1] "X1.Cost" "X1.Month"

对列表使用 [[]]

  print(ggplot(as.data.frame(fd[[i]]), aes(Month, Cost)) +

要回答您的其他问题,您必须创建一个带有地块编号的新变量。这里我使用 rep

f.df$plot_number <-rep(1:round(nrow(f.df)/60),each=60,len=nrow(f.df))

然后,您循环创建一个地块列表

plots <- list()  # new empty list
for (i in unique(f.df$plot_number)) {
 p = ggplot(f.df[f.df$plot_number==i,], aes(Month, Cost))   +
 geom_line(colour = "darkred", size = .5) +
 geom_point(colour = "red", size = 1) +
 labs(x = "Projected Future Costs (monthly)", y = "Dollars") +
 theme_bw() +
 theme(plot.title = element_text(hjust = 0.5)) +
 theme(axis.text.x = element_text(angle = 60, vjust = .6))
 plots[[paste0("p",i)]] <- p  # add each plot into plot list
}

使用软件包 gridExtra,您可以将您的地块安排在一个单独的地块中。

    library(gridExtra)
    do.call("grid.arrange", c(plots, ncol=1))