custom R Markdown plot size within loop

你离开我真会死。 提交于 2020-01-24 01:09:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!