循环内的自定义R Markdown图大小 [英] custom R Markdown plot size within loop

查看:112
本文介绍了循环内的自定义R Markdown图大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在R Markdown/knittr文档中创建带状图.我希望图的垂直大小与带状图中的行数成正比.

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.

最佳解决方案还将允许表格和图表的交织.请参见在循环内在R Markdown中交错表和图

The best solution would also allow interleaving of tables and plots. See Interleaving tables and plots in R Markdown, within loop

在此示例中,"3个化油器"汽车的MPG图与"2个化油器"汽车的图高度相同,即使2个化油器汽车有三种不同的齿轮配置,而对于3个化油器汽车则只有一个. 3-化油器车.

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

推荐答案

以下是使用grid.arrange的解决方案

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)))

```

这篇关于循环内的自定义R Markdown图大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆