修复RMarkdown doc中的ggplot面板宽度

时间:2017-10-30 21:47:07

标签: r ggplot2 knitr r-markdown

我想在RMarkdown文档中的某些ggplots中对齐面板的宽度。我可以通过将图例移动到顶部或底部来实现,但这并不理想。有没有办法用右边的图例指定面板宽度?

---
output: html_document
---

```{r}
library(ggplot2)
d <- data.frame(x = c("a", "b"), fill = c("short", "labels"))
ggplot(d, aes(x = x, fill = fill)) + 
  geom_bar()
```

```{r}
d$fill <- c("Now the labels are longer", "which compresses the plotting area")
ggplot(d, aes(x = x, fill = fill)) + 
  geom_bar()
```

产地: html output

3 个答案:

答案 0 :(得分:2)

egg::set_panel_size可能有所帮助。这有点不方便,因为你需要相应地调整块的宽度,这需要在较早的块中创建绘图。

---
output: html_document
---

```{r}
library(ggplot2)
library(egg)
library(grid)
d <- data.frame(x = c("a", "b"), fill = c("short", "labels"))
p1 <- ggplot(d, aes(x = x, fill = fill)) + geom_bar()
d$fill <- c("Now the labels are longer", "which compresses the plotting area")
p2 <- ggplot(d, aes(x = x, fill = fill)) + 
  geom_bar()
g1 <- egg::set_panel_size(p1, width=unit(4,"in"))
g2 <- egg::set_panel_size(p2, width=unit(4,"in"))
w1 <- convertWidth(sum(g1$widths), "in", TRUE)
w2 <- convertWidth(sum(g2$widths), "in", TRUE)
```

```{r, fig.width=w1}
p1
```

Some text.

```{r,fig.width=w2}
p2
```

enter image description here

答案 1 :(得分:1)

另一种选择是使用grid.arrange包中的gridExtra提取图例并将其作为单独的grob(图形对象)进行布局。这样,只要两个图中的widths参数在grid.arrange中相同,就可以获得两个图的绘图区域相同的面板大小。

---
output: html_document
---

```{r, include=FALSE}
library(ggplot2)
library(gridExtra)
knitr::opts_chunk$set(echo=FALSE)

# Extract the plot legend as a separate grob
# http://stackoverflow.com/questions/12539348/ggplot-separate-legend-and-plot
g_legend<-function(a.gplot){
  tmp <- ggplot_gtable(ggplot_build(a.gplot))
  leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
  legend <- tmp$grobs[[leg]]
  legend
}

thm = theme(legend.justification="left")

widths = c(8,5)
```

```{r}
d <- data.frame(x = c("a", "b"), fill = c("short", "labels"))
p1 = ggplot(d, aes(x = x, fill = fill)) + 
  geom_bar() +
  thm

leg = g_legend(p1)

grid.arrange(p1 + guides(fill=FALSE), leg, widths=widths)
```

```{r}
d$fill <- c("Now the labels are longer", "which compresses the plotting area")
p1 = ggplot(d, aes(x = x, fill = fill)) + 
  geom_bar() +
  thm

leg = g_legend(p1)

grid.arrange(p1 + guides(fill=FALSE), leg, widths=widths)
```

enter image description here

答案 2 :(得分:0)

有些软件包允许您根据需要排列图表。 看一下egg:ggarrange函数。

---
output: html_document
---

```{r}
library(ggplot2)
library(grid)
library(gridExtra)
library(egg)


d <- data.frame(x = c("a", "b"), fill = c("short", "labels"))
p1 <- ggplot(d, aes(x = x, fill = fill)) + 
  geom_bar() 
```

```{r}
d$fill <- c("Now the labels are longer", "which compresses the plotting area")
p2 <- ggplot(d, aes(x = x, fill = fill)) + 
  geom_bar() 
```

```{r}
grid.draw(ggarrange(p1, p2, heights = c(1, 1)))
```

ggarrange example