问题
I'm creating strip plots within a R Markdown/knittr document. I would the like vertical size of the plots to be proportional to the number of rows in the strip plot.
EDIT: The best solution would also allow interleaving of tables and plots. See Interleaving tables and plots in R Markdown, within loop
In this example, the plot for MPG for cars with "3 Carburetors" is the same height as the plot for cars with "2 Carburetors", even though there are three different gear configurations for 2-Carburetor cars and only one for 3-Carburetor cars.
```{r cars, echo=FALSE}
library(ggplot2)
carb.possibilities <- sort(unique(as.character(mtcars$carb)))
filtereds <- lapply(carb.possibilities, function(carb.ct) {
return(mtcars[ mtcars$carb == carb.ct , ])
})
carb.possibilities <- paste(carb.possibilities, ' Carburetors', sep = '')
names(filtereds) <- carb.possibilities
lapply(carb.possibilities, function(one.possibility) {
current.possibility <- filtereds[[one.possibility]]
ggplot(current.possibility, aes(factor(gear), mpg)) +
coord_flip() +
labs(x = "Gears", title = one.possibility) +
geom_point(position=position_jitter( width = 0.1, height = 0.1) )
})
```
回答1:
Here is a solution using grid.arrange
```{r cars, echo=FALSE, fig.height=30}
library(ggplot2); library(gridExtra)
carb.possibilities <- sort(unique(as.character(mtcars$carb)))
filtereds <- lapply(carb.possibilities, function(carb.ct) {
return(mtcars[ mtcars$carb == carb.ct , ])
})
carb.possibilities <- paste(carb.possibilities, ' Carburetors', sep = '')
names(filtereds) <- carb.possibilities
p <- list()
k <- 1
heights <- c()
for(one.possibility in carb.possibilities){
current.possibility <- filtereds[[one.possibility]]
heights[k] <- length(unique(current.possibility$gear))
p[[k]] <- ggplot(current.possibility, aes(factor(gear), mpg)) +
coord_flip() +
labs(x = "Gears", title = one.possibility) +
geom_point(position=position_jitter( width = 0.1, height = 0.1))
k <- k + 1
}
do.call(grid.arrange, c(p, list(ncol = 1, heights= heights)))
```
来源:https://stackoverflow.com/questions/39779573/custom-r-markdown-plot-size-within-loop