循环内的自定义R Markdown绘图大小

时间:2016-09-29 20:38:31

标签: r plot rstudio knitr r-markdown

我正在R Markdown / knittr文档中创建条带图。我希望绘图的垂直大小与条形图中的行数成比例。

编辑:最佳解决方案还允许交错表格和图表。请参阅Interleaving tables and plots in R Markdown, within loop

在这个例子中,具有“3化油器”的汽车的MPG曲线与具有“2化油器”的汽车的曲线高度相同,即使有2种化油器汽车有三种不同的齿轮配置,只有一种用于3-Carburetor汽车。

enter image description here

enter image description here

```{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 个答案:

答案 0 :(得分:1)

这是使用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)))

```