### 如何在R中将ggplot2 x轴可读性分为300个月分成60组

74 观看

1回复

15 作者的声誉

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

### 回应 (1)

0

12986 作者的声誉

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

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

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