knitr plot not showing - basic example - rstudio

I am trying out Knitr with RStudio. The output of plot() is now showing up in the compiled PDF.
Below is an example. The code shows up in the PDF, but not the plot.
\documentclass[11pt]{article}
\begin{document}
\SweaveOpts{concordance=TRUE}
<<my-label, eval=TRUE>>=
plot(1:20)
#
\end{document}
I'm not sure what I'm missing here?

Your example doesn't work for me as is, but if I comment out \SweaveOpts{concordance=TRUE} and click 'Compile PDF', it works (and I can see the plot).
(Note that I too am using Knitr with pdfLaTeX within RStudio.)

Related

Different rendering between .Rmd and .Rmarkdown when using blogdown

I have found some strange differences in the way .Rmd files are rendered compared to .Rmarkdown.
My setup:
Beautiful hugo theme
Blogdown 0.9
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows >= 8 x64 (build 9200)
If change the file extension between Rmd and Rmarkdown, I observe the following differences:
Rmd doesn't render multi level lists properly
Rmd doesn't render footnotes [^1] properly
Rmarkdown doesn't render math properly
Python code chunks don't have a nice little execute button in the upper right in Rmd.
Is this expected behavior? Is there something with the theme that causes this?
Yes the difference between .Rmd and .Rmarkdown is expected and Yihui et al. outlines it in their book (it's around the middle of the page)
You cannot use Markdown features only supported by Pandoc, such as fenced Divs.
Math expressions only work if you apply the JavaScript solution mentioned in Section B.3.
The main thing to note is that .Rmarkdown gets converted to .markdown documents first and gets passed onto Hugo's Markdown renderer (e.g., Goldmark or Blackfriday) to generate a html while .Rmd uses Pandoc by default.

Export PDF: font not found

I am trying to export my figure as a PDF. I run into the problem that when I want to edit it (in this case by Graphic on macOS) that the font appears not to be found by the editor. My question is, how do I solve this? Can I 'install' the fonts used by matplotlib?
Example
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([0,1], [0,1])
plt.savefig('test.pdf')
This PDF looks fine in Preview:
But in the editor, it gives gibberish:
Failing solution
Setting
matplotlib.rc("pdf", fonttype=42)
(see this answer).
Partly working solution
What works is to install all matplotlib's fonts. I have followed this answer to find all matplotlib's ttfs, and installed them. This works and solves the problem.
But... This does solve the issues when LaTeX is enabled, by
import matplotlib
matplotlib.rcParams['text.usetex'] = True
How do I install the fonts that matplotlib uses now?
A solution here is to export as SVG. However, for some reason this takes ages on my system (see this bug).
I have found a workaround. This is to convert all fonts to outlines before editing. One way to do this is with GhostScript with the option -dNoOutputFonts, as described in this answer:
gs -o file-with-outlines.pdf -dNoOutputFonts -sDEVICE=pdfwrite file.pdf
What pdf editor are you using? I don't know how to check whether an attempt to solve this is working... but I always use this code to save images in pdf or png:
plt.savefig('test.pdf', edgecolor='none', bbox_inches="tight")

How to set size for local image using knitr for markdown?

I have a local image that I would like to include in an .Rmd file which I will then knit and convert to HTML slides with Pandoc. Per this post, this will insert the local image :
![Image Title](path/to/your/image)
Is there a way to modify this code to also set the image size?
The question is old, but still receives a lot of attention. As the existing answers are outdated, here a more up-to-date solution:
Resizing local images
As of knitr 1.12, there is the function include_graphics. From ?include_graphics (emphasis mine):
The major advantage of using this function is that it is portable in the sense that it works for all document formats that knitr supports, so you do not need to think if you have to use, for example, LaTeX or Markdown syntax, to embed an external image. Chunk options related to graphics output that work for normal R plots also work for these images, such as out.width and out.height.
Example:
```{r, out.width = "400px"}
knitr::include_graphics("path/to/image.png")
```
Advantages:
Over agastudy's answer: No need for external libraries or for re-rastering the image.
Over Shruti Kapoor's answer: No need to manually write HTML. Besides, the image is included in the self-contained version of the file.
Including generated images
To compose the path to a plot that is generated in a chunk (but not included), the chunk options opts_current$get("fig.path") (path to figure directory) as well as opts_current$get("label") (label of current chunk) may be useful. The following example uses fig.path to include the second of two images which were generated (but not displayed) in the first chunk:
```{r generate_figures, fig.show = "hide"}
library(knitr)
plot(1:10, col = "green")
plot(1:10, col = "red")
```
```{r}
include_graphics(sprintf("%sgenerate_figures-2.png", opts_current$get("fig.path")))
```
The general pattern of figure paths is [fig.path]/[chunklabel]-[i].[ext], where chunklabel is the label of the chunk where the plot has been generated, i is the plot index (within this chunk) and ext is the file extension (by default png in RMarkdown documents).
Un updated answer: in knitr 1.17 you can simply use
![Image Title](path/to/your/image){width=250px}
edit as per comment from #jsb
Note this works only without spaces, e.g. {width=250px} not {width = 250px}
You can also read the image using png package for example and plot it like a regular plot using grid.raster from the grid package.
```{r fig.width=1, fig.height=10,echo=FALSE}
library(png)
library(grid)
img <- readPNG("path/to/your/image")
grid.raster(img)
```
With this method you have full control of the size of you image.
Here's some options that keep the file self-contained without retastering the image:
Wrap the image in div tags
<div style="width:300px; height:200px">
![Image](path/to/image)
</div>
Use a stylesheet
test.Rmd
---
title: test
output: html_document
css: test.css
---
## Page with an image {#myImagePage}
![Image](path/to/image)
test.css
#myImagePage img {
width: 400px;
height: 200px;
}
If you have more than one image you might need to use the nth-child pseudo-selector for this second option.
If you are converting to HTML, you can set the size of the image using HTML syntax using:
<img src="path/to/image" height="400px" width="300px" />
or whatever height and width you would want to give.
Had the same issue today and found another option with knitr 1.16 when knitting to PDF (which requires that you have pandoc installed):
![Image Title](path/to/your/image){width=70%}
This method may require that you do a bit of trial and error to find the size that works for you. It is especially convenient because it makes putting two images side by side a prettier process. For example:
![Image 1](path/to/image1){width=70%}![Image 2](path/to/image2){width=30%}
You can get creative and stack a couple of these side by side and size them as you see fit. See https://rpubs.com/RatherBit/90926 for more ideas and examples.
Another option that worked for me is playing with the dpi option of knitr::include_graphics() like this:
```{r}
knitr::include_graphics("path/to/image.png", dpi = 100)
```
... which sure (unless you do the math) is trial and error compared to defining dimensions in the chunk, but maybe it will help somebody.
The knitr::include_graphics solution worked well for resizing the figures, but I was unable to figure out how to use it to produce side-by-side resized figures. I found this post useful for doing so.

Error including multiple images in Latex

While compiling the following code
{\centering {\includegraphics[scale=.5]{splash.eps}} \caption{Splash Screen} \par}
\end{figure}
Splash screen is an integral part and shows a tutorial of application.
\begin{figure}[ht]
{\centering {\includegraphics[scale=.5]{splashmore.eps}} \caption{Splash Screen 1} \par}
\end{figure}
The first image (i.e splash.eps) gets added properly when compiled. While trying to add the second one, compilation gives the following error.
! LaTeX Error: Cannot determine size of graphic in ./eps/splashmore.eps (no Bou
ndingBox).
See the LaTeX manual or LaTeX Companion for explanation.
Type H <return> for immediate help.
...
l.16 ...\includegraphics[scale=.5]{splashmore.eps}
} \caption{Splash Screen 1...
What could be the problem?
Edit: The problem was with the image. I opened it with Gimp and saved it as .eps file and latter on used it with no troubles.
The problem could be that splashmore.eps has no Bounding Box (like the error message says). You could either
add the bounding box information manually (see here for a description of what a bounding box is and how to do that) or
use a tool: Opening your file in a vector graphics editor and saving it (again) as eps could help, otherwise you could use epstool.
I guess you could try to add width=5cm as argument to includegraphics. Don't know if that is satisfactory though.

Blurred colors using epsfig or graphicx in LaTeX

My code is simple enough, and importing eps images is something I've done before with other matlab-generated content, but for one reason or another I end up with blurred colors in my heatmap when I use epsfig or graphicx to import it into my document. In the picture below, the right is what shows up if I compile to DVI and open up the document in Yap, and the left is if I simply view the eps in GSView.
alt text http://img85.imageshack.us/img85/1694/epsproblem.png
Here is my code. This example is using graphicx, but the idea is the same with epsfig.
\begin{figure}
\centering
\includegraphics[scale=0.5]{images/ngram3_model_raw.eps}
\caption{The perplexity when compared
against the HUB test set}
\end{figure}
Is there perhaps some option I am forgetting?
I had the same problem with DVI, but if I compiled to pdf the pictures were fine
What you see is bilinear interpolation. It is done by the viewer. Probably Matlab defines the plot contents as a pixmap (I guess you use imagesc?).
The solution is not straightforward. It may help to use a different processing chain (as WtFudgE pointed out) that will lead the data end up in a format where it is not interpolated anymore. You may also use a different viewer that does not interpolate and I would assume that a printer would also not interpolate. This can again be dependent of the application you print from.
Sorry that I don't have a solution for you; at least you now have some new words to search for in Google. ;)

Resources