title: How to put the figures and tables in the right places using knitr, rstudio and Sweave to generate a pdf?
body: <p>I am trying to use knitr and RStudio to generate a pdf. My question is: I cannot put the figures and tables in the right places. Please take a look at this simple example:</p>
  
  <pre><code>\documentclass{article}
  \linespread{1}
  \usepackage{longtable}
  \usepackage{caption}
  
  \title{\textbf{\large{Reports: }}}
  \author{\large{***}}
  
  \begin{document}
  \maketitle
  
  &lt;&lt;echo= F,message = F,warning = F&gt;&gt;=
  # Set the global chunk options
  opts_chunk$set(echo = F, # Do NOT repeat code in final document
                 message = F, # Do NOT print R messages in document
                 warning = F # Do NOT print warnings
                 )
  library(dplyr)
  library(ggplot2)
  library(xtable)
  library(stringr)
  @
  
  \section*{\large{Overview}}  %with *, then no number
  &lt;&lt;&gt;&gt;=
  myWhole &lt;- data.frame(x=c(1,2,3,4),y=c(2,3,4,5))
  @
  \begin{figure}
  &lt;&lt;echo = F, fig.width = 4, fig.height = 1.5, fig.align = 'center'&gt;&gt;=
  ggplot(myWhole,aes(x=x,y=y)) + 
    geom_point()
  @
  \setlength{\abovecaptionskip}{-1pt}
  \captionsetup{justification=centering}
  \caption{****}
  \end{figure}
  \section*{\large{Query 6: ***}}
  just try...just try...just try...just try...just try...just try...just     try...just try...
  \begin{table}
  \setlength{\abovecaptionskip}{-10pt}
  \captionsetup{justification=centering}
  \caption{}
  &lt;&lt;echo=FALSE,results='asis',message=FALSE&gt;&gt;=
  xt=xtable(myWhole)
  print(xt,tabular.environment="longtable",floating=F)
  @
  \end{table}
  \end{document}
  </code></pre>
  
  <p>You can see the figure belongs to the first section and the table belongs to the second. I hope the order should be: </p>
  
  <pre><code>section title: Overview
  words
  figure
  words
  section title: query 6
  words
  table
  words
  </code></pre>
  
  <p>But the generated PDF looks like this:</p>
  
  <p><a href="https://i.stack.imgur.com/NvLgB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NvLgB.png" alt="enter image description here"></a></p>
  
  <p>Even this picture is not clear, you can still see that they are not in the right places. And the table is on the second page although there is plenty room on the first page. Could anyone please help me here?</p>