问题
I would like to have plots generated by ggplot2 inserted into a LaTeX document with the panel as wide as \textwidth
(or \columnwidth
in a two column document). I have the following solution:
\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}
However, the solution does not work when a legend is added:
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"))
The legend messes up the alignment. Setting the pos
argument in \makebox
won't work as the background is off-centre. I understand I could put the legend atop the chart, but I'd prefer to have the option to have the legend intrude into the margin.
回答1:
you'll probably find it easier to query sizes if you work with the 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]
来源:https://stackoverflow.com/questions/36097391/align-panel-background-instead-of-plot-background-with-document-margins