使用文档边距对齐panel.background而不是plot.background

时间:2016-03-19 03:13:08

标签: ggplot2 latex knitr

我想将ggplot2生成的绘图插入到LaTeX文档中,面板的宽度与\textwidth(或两列文档中的\columnwidth一样宽)。我有以下解决方案:

\documentclass{article}
\usepackage{lipsum, graphicx}

<<knitrOpts, echo=FALSE>>=
knitr::opts_chunk$set(echo = FALSE,
                      fig.show = 'hide',
                      fig.width=general_fig_width <- 5, 
                      fig.height=3, 
                      out.width = out_width <- "5in",
                      out.height="3in"
                      )
@
\usepackage{geometry}

\setlength{\textwidth}{\Sexpr{out_width}}

<<loadPackages>>=
library(ggplot2)
library(dplyr)
library(grid)
@

\begin{document}
<<plot>>=
diamonds %>%
  sample_frac(0.3) %>%
  ggplot(aes(x = carat, y = price)) + 
  geom_point() + 
  theme_dark() + 
  theme(plot.margin = unit(c(0,0,0,0), "pt"))

grid.ls(view=TRUE,grob=FALSE)
current.vpTree()
seekViewport('panel.3-4-3-4')
a <- convertWidth(unit(1,'npc'), 'inch', TRUE)


width_factor <-  general_fig_width / a
@

\lipsum
\begin{figure}[t]
\makebox[\textwidth][r]{\includegraphics[width=\Sexpr{width_factor}\textwidth]{figure/plot-1}}
\end{figure}
\lipsum

\end{document}

enter image description here

但是,添加图例时解决方案不起作用:

diamonds %>%
  sample_frac(0.3) %>%
  ggplot(aes(x = carat, y = price, color = price)) + 
  geom_point() + 
  theme_dark() + 
  theme(plot.margin = unit(c(0,0,0,0), "pt"))

enter image description here

传说弄乱了对齐方式。在pos中设置\makebox参数将不起作用,因为背景偏离中心。我知道我可以将图例放在图表的顶部,但我更愿意让图例进入边缘。

1 个答案:

答案 0 :(得分:4)

如果你使用gtable,你可能会发现查询大小更容易,

---
title: "Untitled"
header-includes:
   - \usepackage{lipsum}
output: 
  pdf_document: 
    fig_caption: yes
    fig_crop: no
    keep_tex: yes
geometry: width=5in
---

```{r setup, include=FALSE}
library(ggplot2)
library(dplyr)
library(grid)
library(knitr)
general_fig_width <- 5
```

```{r plot, fig.show=FALSE}
p <- diamonds %>%
  sample_frac(0.3) %>%
  ggplot(aes(x = carat, y = price, color = price)) + 
  geom_point() + 
  theme_dark() + 
  theme(plot.margin = unit(c(0,0,0,0), "pt"))

g <- ggplotGrob(p)

if(getRversion() < "3.3.0"){
  g$widths <- grid:::unit.list(g$widths)
  g$widths[4] <- list(unit(general_fig_width, "in"))
} else {
  g$widths[4] <- unit(general_fig_width, "in")
}
fig_width <- convertWidth(sum(g$widths), "in", valueOnly = TRUE)
left_width <- convertWidth(sum(g$widths[1:3]), "in", valueOnly = TRUE)
ggsave('plot-tmp.pdf', width=fig_width, height=2)
```

\begin{figure}[!hb]
\hspace{`r -left_width`in}\includegraphics[width=`r fig_width`in]{plot-tmp}
\end{figure}

\lipsum[2]

enter image description here