8
votes

Using knitr and markdown packages to weave Rmd files to markdown and then html is producing some unexpected behavior in the way that ggplot2 graphs are appearing in the final html file.

For example, using the following Rmd file diamond.Rmd

# ggplot2 graph shows up fainter, and text smaller

```{r echo=FALSE, message=FALSE, warning=FALSE}   
opts_chunk$set(fig.width=18, fig.height=10)
require(ggplot2)
```

***

# Simple Plot
```{r echo=FALSE, message=FALSE, warning=FALSE}   
data(diamonds)
g <- ggplot(diamonds, aes(carat, depth, colour=color)) + geom_point() + facet_wrap(~cut)
g 
```

with this file knit.R

require(markdown)
require(knitr)
knit('diamonds.Rmd')
markdownToHTML('diamonds.md', 'diamonds.html', options=c('base64_images'))
browseURL(paste('file://', file.path(getwd(), 'diamonds.html'), sep=''))

I've taken a screeenshot of the plot in the html file and included it below (is there a better way to show this?):

plot from html file

The plot inside the html file is lighter, ie the color is less dark. Also, the text on the plot, including the axis labels and the tick mark labels are smaller and lighter, making them very difficult to read.

If you look at the plot created directly from R, you'll see it doesn't have those problems.

plot directly from R

I'm guessing this is some issue with my graphical device or the graphics device that knitr is using.

Is there a way to force the plots that eventually end up in the html file to keep the original plot appearance, ie to stay darker and have larger text?

1
Thanks for asking. I am also having the same issue - the quality of ggplot2 graphs generated with Rmarkdown/kintr in RStudio in the html format is very poor compared to the regular pdf or png devices. Using the device="png"/"pdf" option saves these plots in new folder called figures, but they are also of poor quality.Vijay Ivaturi
the issue is the width and height you have specified. if you use fig.width = 7 and fig.height = 7, you should get the same results as in the console, since it is the default. Note that you can use dpi option to control the pixel size, but be careful since the eventual size will be dpi x width.Ramnath
if you want to retain the same figure size but have a higher pixel size use fig.width = 9, fig.height = 5 and dpi = 144 (the default dpi is 72). This would give you a plot of the same size but with bigger pixels and text.Ramnath

1 Answers

4
votes

As suggested by @Ramnath:

If you want to retain the same figure size but have a higher pixel size use:

fig.width = 9, fig.height = 5, dpi = 144

The default dpi is 72, this would give you a plot of the same size but with bigger pixels and text.