将panel.background而不是plot.background与文档边距对齐 [英] Align panel.background instead of plot.background with document margins
问题描述
我想将ggplot2生成的图插入到LaTeX文档中,面板的宽度为\textwidth
(或两列文档中的\columnwidth
).我有以下解决方案:
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"))
图例弄乱了对齐方式.由于背景偏心,因此在\makebox
中设置pos
参数将不起作用.我知道我可以将图例放在图表的顶部,但我更愿意选择使图例侵入页边.
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.
推荐答案
如果使用gtable,您可能会发现更容易查询大小,
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]
这篇关于将panel.background而不是plot.background与文档边距对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!