如何使fig.width和out.width与knitr一致?

Cle*_*ter 5 latex r tikz knitr

我最近发现了knitr,我主要用它来制作dev=tikz用于轻松进行乳胶排版的图.但是我不明白如何设置块选项fig.widthout.width一致性.

我的意思是,我知道第一个是R选项,而第二个是乳胶选项,\includegraphics但似乎如果fig.width太大,out.width那么线条非常薄,因为乳胶缩小了图片.另一方面,如果它太小,那么乳胶会拉伸它,而且一切都太大了.

基本上我也想有一个设置,我只选择out.width,然后行和文本的厚度与文档的文本大小一致.

我包括一个MWE来说明我的问题.另外我已经设置fig.height了第一个例子,否则图片比页面大,我也不太明白这一点.

热烈欢迎任何帮助!

\documentclass[12pt,a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage[english]{babel}
\usepackage[T1]{fontenc}
\usepackage{graphicx}

<<setup, include=FALSE, cache=FALSE>>=
  library(knitr)
  options(formatR.arrow=TRUE,width=50)
  opts_chunk$set(fig.path='figure/graphics-', 
                 cache.path='cache/graphics-', 
                 fig.align='center', 
                 dev='tikz')
@

\begin{document}
\begin{figure}[!ht]
    <<fig_1,fig.width=2,  fig.height = 3,out.width = '\\textwidth',echo=FALSE>>=
    x = seq(1,3,l=100)
    plot(x,cos(x), type ="l", xlab = "x", ylab = "y")
    @
\end{figure}
\begin{figure}[!ht]
<<fig_2,fig.width=10,  out.width = '\\textwidth',echo=FALSE>>=
    x = seq(1,3,l=100)
    plot(x,cos(x), type ="l", xlab = "x", ylab = "y")
    @
\end{figure}

\end{document}
Run Code Online (Sandbox Code Playgroud)

Cle*_*ter 6

基本上,tikzpicture在创建之后不应该进行大小调整,因为它将与文本样式失去一致性.事实上,当cache=FALSE设置了chunk选项时,则out.width没有效果,因为没有创建pdf输出.因此,人们必须在指定的确切英寸的措施fig.width,并fig.height为每个块.

在对stackoverflow和Knitr网站进行了一些研究之后,我发现了一个几乎相同用户实验的技巧,即我不想关心实际大小但只考虑相对于\textwidth其他Latex变量:

  • 在设置块中,使用显式名称定义R变量(例如paperwidth,textwidth对应于以英寸为单位的Latex,例如A4纸是(w,h)=(8.3,11.7).
  • 在每个带有绘图的块中,您可以使用fig.width = 0.5*paperwidth例如

这是一个MWE:

\documentclass[12pt,a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage[english]{babel}
\usepackage[T1]{fontenc}
\usepackage{graphicx}
\usepackage{tikz}
<<setup, include=FALSE, cache=FALSE>>=
  library(knitr)
  options(formatR.arrow=TRUE,width=50)
  opts_chunk$set(fig.path='figure/graphics-', 
                 cache.path='cache/graphics-', 
                 fig.align='center',
                 dev='tikz',
                 external=TRUE,
                 echo=FALSE
                )
  a4width<- 8.3
  a4height<- 11.7
@

\begin{document}
\begin{figure}[!ht]
\centering
<<fig_1, fig.width = 0.4*a4width, fig.height = 0.2*a4height>>=
    x = seq(1,3,l=100)
    plot(x,cos(x), type ="l", xlab = "x", ylab = "y")
@

<<fig_2, fig.width = 0.2*a4width, fig.height = 0.5*a4height>>=
    x = seq(1,3,l=100)
    plot(x,cos(x), type ="l", xlab = "x", ylab = "y")
@

\caption{Test figure}
\end{figure}
\end{document}
Run Code Online (Sandbox Code Playgroud)