2017-12-28 38 views
1

knitR(.Rnw)を使用してレポートを作成し、PDFとしてコンパイルしました。 1つの質問ごとに同じ数字をプロットしたいので、私はfor-loopでプロットを作成しました。残念ながら、PDFで警告が表示され、エラーの原因を実際には取得しないでください。forループでggplotを使用したプロットがPDFにコンパイルされない

ここでは、問題が始まると思われるチャンクがあります。ループはR内でうまく動作しますが、PDFとしてコンパイルされません以下のコード全体を参照してください)。私は様々なラベル、印刷機能などを試しましたが、解決策を見つけることができませんでした。ここで

<<echo=FALSE, warning=T, message=F>>= 

for(i in 1:3){ 
    cat(paste("\\subsection{",titel[i],"}\n", sep="")) 
    cat(paste("Figure \\ref{class",i,"} \n", sep="")) 
    cat(paste("\\begin{figure}[H] \n", sep="")) 
    cat(paste("\\begin{center} \n", sep="")) 
    cat(paste("\\includegraphics[width=1\\textwidth,", 
      "height=.47\\textheight,keepaspectratio]{class",i,".pdf}\\caption{",titel[i],"}\n", sep="")) 

    cat(paste("\\label{class",i,"}" \n, sep="")) 
    cat(paste("\\end{center} \n",sep="")) 
    cat(paste("\\end{figure} \n",sep="")) 



    p <- ggplot(data[!is.na(data$F17),], aes_string(x=Fragen[i], y="..prop..", group = "1", fill="F17"))+ 
     geom_bar()+ 
     facet_grid(F17~.)+ 
     geom_text(aes(label = scales::percent(..prop..), 
       y= ..prop..), stat= "count", vjust = -.5, size=3) + 
     ylab("Prozent")+ 
     xlab(titel[i])+ 
     scale_fill_manual(name="Individuals", values=colorScheme)#+ 
     #theme_mine 


pdfnam<-paste("class",i,".pdf",sep="") #produce a plot for each class 
pdf(file=pdfnam,width=12, height = 4) 
#gridExtra::grid.arrange(p, q) 
print(p) 
dev.off() 
} 

@ 

複製のための全体のコードです:事前に

\documentclass{article} 

\usepackage{amsmath,amssymb,amstext} 
\usepackage{graphicx} 
\usepackage{geometry} 
\geometry{top=15mm, left=25mm, right=25mm, bottom=25mm,headsep=10mm,footskip=10mm} 
\usepackage{xcolor} 
\usepackage{float} 
\usepackage[T1]{fontenc} % Umlaute 
\usepackage[utf8]{inputenc} 
\inputencoding{latin1} 

\begin{document} 
\parindent 0pt 

\title{title} 
\maketitle 

<<echo=FALSE, warning=FALSE, message=FALSE>>= 
library(ggplot2) 
library(reshape) 
library(knitr) 
library(doBy) 
library(dplyr) 


opts_chunk$set(fig.path='figure/graphic-', fig.align='center', fig.show='hold',fig.pos='!ht', 
      echo=FALSE,warning = FALSE) 

@ 

<<echo=FALSE, warning=FALSE, message=F>>= 

# data and other useful stuff 

data <- data.frame(F1 = c("A", "A", "B", "C"), # answers to question 1, ... 
        F2 = c("A", "B", "B", "C"), 
        F3 = c("A", "B", "C", "C"), 
        F17 = c("K", "L", "L", "M")) # K, L and M are a certain individual. L answered twice. 

# colour scheme: 
GH="#0085CA"; H="#DA291C"; BV="#44697D" 
colorScheme <- c(BV, H, GH) 

# individual theme for plots: 
theme_mine = theme(plot.background = element_rect(fill = "white"), 
       panel.background = element_rect(fill = "white", colour = "grey50"), 
       text=element_text(size=10, family="Trebuchet MS")) 

# a vector with the variable names from "data" (F1, F2, F3). 
Fragen <- c(paste0('F',seq(1:3), sep="")) 

# question title for labeling the plots: 
titel <- c("Q1", "Q2", "Q3", "Q17") 

@ 


\begin{figure}[h] 
\begin{center} 
<<echo=FALSE, fig.width=9.6, fig.height=6, warning=FALSE>>= 

p <- ggplot(data, aes(x=F17))+ 
    geom_bar(fill = colorScheme)+ 
    xlab(titel[4])+ 
    #geom_text(aes(label = scales::percent(..prop..), 
    #   y= ..prop..), stat= "count", vjust = -.5, size=3) + 
    ylab("Absolut")+ 
    theme_bw() 
    #theme_mine # does not work properly yet. 
p 

@ 
\caption{figa} 
\label{figa} 
\end{center} 
\end{figure} 

\section{individual plots} 

<<echo=FALSE, warning=T, message=F>>= 

# here is where the problem starts: the loop runs fine within R but does not compile to an PDF. 

for(i in 1:3){ 
    cat(paste("\\subsection{",titel[i],"}\n", sep="")) 
    cat(paste("Figure \\ref{class",i,"} \n", sep="")) 
    cat(paste("\\begin{figure}[H] \n", sep="")) 
    cat(paste("\\begin{center} \n", sep="")) 
    cat(paste("\\includegraphics[width=1\\textwidth,", 
      "height=.47\\textheight,keepaspectratio]{class",i,".pdf}\\caption{",titel[i],"}\n", sep="")) 

    cat(paste("\\label{class",i,"}" \n, sep="")) 
    cat(paste("\\end{center} \n",sep="")) 
    cat(paste("\\end{figure} \n",sep="")) 



    p <- ggplot(data[!is.na(data$F17),], aes_string(x=Fragen[i], y="..prop..", group = "1", fill="F17"))+ 
     geom_bar()+ 
     facet_grid(F17~.)+ 
     geom_text(aes(label = scales::percent(..prop..), 
       y= ..prop..), stat= "count", vjust = -.5, size=3) + 
     ylab("Prozent")+ 
     xlab(titel[i])+ 
     scale_fill_manual(name="Individuals", values=colorScheme)#+ 
     #theme_mine 


pdfnam<-paste("class",i,".pdf",sep="") #produce a plot for each class 
pdf(file=pdfnam,width=12, height = 4) 
#gridExtra::grid.arrange(p, q) 
print(p) 
dev.off() 
} 

@ 


\end{document} 

おかげでたくさん!

+2

'pdf()'行を削除してください。プロットをスタンドアロンPDFとして保存するために使用され、レポート内にプロットを含めるためには使用されません。 – Gregor

+0

'\ label {abc}'は '\ ref {abc}'を許可します。しかし、 '\ label {figure/class }'( ''の周りに空白がありますが)に '\ ref {}'(やはりスペースを入れて)を使用しています。 – Werner

+0

...また、[\ centering'ではなく '\ begin {center}'を使うべきですか?](https://tex.stackexchange.com/q/23650/5764) '\ centering'を使うべきです。 – Werner

答えて

0

再現可能なスクリプトを使用して伝えたいことがいくつかあります。それを提供してくれてありがとう、それは多くの助けになります。

通常、Rチャンクにplotまたはprint(ggplot_object)がある場合、knitrを使用してグラフを作成できます。あなたの例では begin{Figure}をRコードと混ぜて、プロットオブジェクトを生成してみましょう。あなたはそれを使う必要はありません。 Knitrは、.Rnwスクリプトと同じフォルダにある図形パス(デフォルト)を指し示す完全なプロットオブジェクトを作成するためのツールを提供します。私はあなたの下でそれを行う方法の例を与えています。

唯一の欠点は、あなたのTeXファイルを読み込むしようとした場合、それはのようにきれいにあなたがそのコードを作成したかのようにレンダリングされないことを自分自身である(私が何を意味するかはあなたのTeXファイルを編集 とき、すべてが1であるということです行が、これはknitrの批判ではない、それはちょうど良い)です。やってみたもう1つの選択肢は、Figureを1つのフォルダのどこかに保存し、それをtexコマンドでロードすることです。下の例では、あなたのスクリプトを使用して、この方法で図を含める方法の例を示します。それがあなたに役立つことを願っています。

\documentclass{article} 

\usepackage{amsmath,amssymb,amstext} 
\usepackage{graphicx} 
\usepackage{geometry} 
\geometry{top=15mm, left=25mm, right=25mm, bottom=25mm,headsep=10mm,footskip=10mm} 
\usepackage{xcolor} 
\usepackage{float} 
\usepackage[T1]{fontenc} % Umlaute 
\usepackage[utf8]{inputenc} 
\inputencoding{latin1} 
\usepackage{hyperref} 
\begin{document} 
\parindent 0pt 

\title{title} 
\maketitle 

<<echo=FALSE, warning=FALSE, message=FALSE>>= 
library(ggplot2) 
library(reshape) 
library(knitr) 
library(doBy) 
library(dplyr) 


opts_chunk$set(fig.path='figure/graphic-', fig.align='center', fig.show='hold',fig.pos='!ht', 
      echo=FALSE,warning = FALSE) 

@ 

<<echo=FALSE, warning=FALSE, message=F>>= 

# data and other useful stuff 

data <- data.frame(F1 = c("A", "A", "B", "C"), # answers to question 1, ... 
        F2 = c("A", "B", "B", "C"), 
        F3 = c("A", "B", "C", "C"), 
        F17 = c("K", "L", "L", "M")) # K, L and M are a certain individual. L answered twice. 

# colour scheme: 
GH="#0085CA"; H="#DA291C"; BV="#44697D" 
colorScheme <- c(BV, H, GH) 

# individual theme for plots: 
theme_mine = theme(plot.background = element_rect(fill = "white"), 
       panel.background = element_rect(fill = "white", colour = "grey50"), 
       text=element_text(size=10, family="Trebuchet MS")) 

# a vector with the variable names from "data" (F1, F2, F3). 
Fragen <- c(paste0('F',seq(1:3), sep="")) 

# question title for labeling the plots: 
titel <- c("Q1", "Q2", "Q3", "Q17") 

@ 

First chunk uses the knitr output to place the figures, if you use ggplot don't 
forget to print your plot : \textbf{print(p)} otherwise it won't work . All your 
arguments are passed through chunk options. So where you tried to have them in the text, 
they are simply placed as other options to your chunk (see below). I have used 
the following options to reproduce your example. 
\begin{itemize} 
\item fig.width=9.6 
\item fig.height=6 
\item fig.pos='h', 
\item fig.cap="figa" 
\item fig.lp="figa" 
\item fig.align='center' 
\end{itemize} 

<<echo=FALSE, fig.width=9.6, fig.height=6, warning=FALSE, fig.pos='h', fig.cap="figa",fig.lp="figa", fig.align='center'>>= 

p <- ggplot(data, aes(x=F17))+ 
    geom_bar(fill = colorScheme)+ 
    xlab(titel[4])+ 
    #geom_text(aes(label = scales::percent(..prop..), 
    #   y= ..prop..), stat= "count", vjust = -.5, size=3) + 
    ylab("Absolut")+ 
    theme_bw() 
    #theme_mine # does not work properly yet. 
print(p) 

@ 




\section{individual plots} 

For individual plots we will use your script to generate the figure environment. 
To produce latex you need to pass the option 'asis'. 

<<generate_latex,echo=FALSE, warning=T, message=F, results='asis'>>= 
for(i in 1:3){ 
    cat(paste("\\subsection{",titel[i],"}\n", sep="")) 
    cat(paste("Figure \\ref{class",i,"} \n", sep="")) 
    cat(paste("\\begin{figure}[H] \n", sep="")) 
    cat(paste("\\begin{center} \n", sep="")) 
    cat(paste("\\includegraphics[width=1\\textwidth,", 
      "height=.47\\textheight,keepaspectratio]{class",i,".pdf}\\caption{",titel[i],"}\n", sep="")) 
    cat(paste("\\label{class",i,"} \n", sep="")) 
    cat(paste("\\end{center} \n",sep="")) 
    cat(paste("\\end{figure} \n",sep="")) 
} 
@ 
Now we need to save those figures. By default in knitr figures are saved in the \textit{figure} 
subfolder and path is set to \textit{figure/myfigure} in the includegraphics 
command in the tex file. 

<<plot,echo=FALSE, warning=T, message=F, fig.keep='all',fig.show='hide', results='hide'>>= 
for(i in 1:3){ 
    p <- ggplot(data[!is.na(data$F17),], aes_string(x=Fragen[i], y="..prop..", group = "1", fill="F17"))+ 
     geom_bar()+ 
     facet_grid(F17~.)+ 
     geom_text(aes(label = scales::percent(..prop..), 
       y= ..prop..), stat= "count", vjust = -.5, size=3) + 
     ylab("Prozent")+ 
     xlab(titel[i])+ 
     scale_fill_manual(name="Individuals", values=colorScheme)#+ 
     #theme_mine 
    print(p) 
} 
@ 
Now the other way to do it, as in sweave is just to save the plot where you 
want, this is the old sweave way, which I tend to use, I gave some explanation 
on how to arrange folders 
\href{https://stackoverflow.com/questions/46920038/how-to-get-figure-floated-surrounded-by-text-etc-in-r-markdown/46962362#46962362}{example script} 
In sweave you save those files using pdf() or png() or 
whatever device and set the graphics path to those figures using 
\textit{\\graphicspath{{/figure}}} in the preamble. If you want to set your 
graphics path to another folder you can set path using command like 
\textit{\\graphicspath{{../../figure}}}. This will set your path to the 
grandparent folder. 

Here I'm creating a directory, if existing, the code will still proceed with no 
warnings : \textit{dir.create(imagedir, showWarnings = FALSE)}. 

<<plot_manual,echo=FALSE, warning=T, message=F,results='hide'>>= 
imagedir<-file.path(getwd(), "figure") 
dir.create(imagedir, showWarnings = FALSE) # use show warning = FALSE 
pdfnam<-paste0(imagedir,"/class4.pdf") #produce a plot for each class 
pdf(file=pdfnam,width=8, height = 4) 
for(i in 4){ 
    p <- ggplot(data[!is.na(data$F17),], aes_string(x=Fragen[i], y="..prop..", group = "1", fill="F17"))+ 
     geom_bar()+ 
     facet_grid(F17~.)+ 
     geom_text(aes(label = scales::percent(..prop..), 
       y= ..prop..), stat= "count", vjust = -.5, size=3) + 
     ggtitle("manually saved plot")+ 
     ylab("Prozent")+ 
     xlab(titel[i])+ 
     scale_fill_manual(name="Individuals", values=colorScheme) 
    print(p) 
} 
dev.off() 
@ 
\subsection{section 4} 
This is Figure \ref{class4} 
\begin{figure}[H] 
\begin{center} 
    \includegraphics[width=1\textwidth,height=.47\textheight,keepaspectratio]{figure/class4.pdf} 
    \caption{Manually edited caption for figure 4} 
    \label{class4} 
    \end{center} 
\end{figure} 

\end{document} 
+0

魅力のように動作します、ありがとうございます!もう1つの質問。私が最初の解決策の中で私のプロットのサイズを変更したいのであれば、私は 'includegraphics [...]'の中でこれをしなければならないと思います。残念ながら私はプロットの縮尺を変えることができます。 。これにはきちんとした解決策がありますか?また、私が望むところでプロットを保存する2番目のソリューションもあります。私はすべてのプロットのfor-loopでこれをやりたいのですが、私はLatex情報をforループに入れなければなりません(別のチャンク)もう一度?再び、ありがとう! – klamsi

+0

ニットでは、[fig.width、fig.heigh](https://yihui.name/knitr/options/)のオプションがありますが、ラスタ画像またはPNG画像を使用している場合は注意してください。[SO post](https:///stackoverflow.com/questions/32748235/how-to-remove-white-space-above-and-below-image-in-r-markdown/47429265#47429265)。ラテックス出力の場合は、グラフをpdfとして保存することが最善ですが、まずx11()などのデバイスウィンドウ内でプロットが良好であるかどうかを確認します。 'dev.size()'でデバイスのサイズを取得します。それらの引数をknitrで使用します。 – Cedric

+0

2番目の質問に答えるために、たくさんの数字を生成する必要がある場合は、おそらくループからラテックスコードを生成する意味があります。カテゴリごとにレポートを動的に生成する場合(国ごとのグラフ...地域ごとなど)です。私は最終的なレポートでは、多くのグラフを生成することはしませんが、それらを\ subfigure環境に埋め込むことが多いことがわかりました。だから私は私の人物を磨くために多くの時間を費やしてから、私の報告書の中で(ニットではなく)直接\ figure環境を作ります。 – Cedric

関連する問題