Unwanted stripes in ggplot2 histogram when knitting with pdf
When pasting a simple histogram into the pdf, I am getting some unwanted bands in my bars (see the right side of the attached screenshot).
---
title: "Don't Panic"
author: "Ford Perfect"
output: pdf_document
---
```{r, include = F}
library(ggplot2)
```
# Introduction
```{r, echo = F, fig.cap = "My plot"}
ggplot(mpg) + geom_bar(aes(x = as.factor(cyl), y = hwy), stat="identity")
```
These bars do not appear when I create the graph directly in R-Studio (see the left side of the screenshot).
I found a way to remove these stripes by aggregating the data to:
ggplot(aggregate(hwy~cyl,mpg,"sum")) +
geom_bar(aes(x = as.factor(cyl), y = hwy), stat="identity")
So my understanding is that these bands should come from stacking all the other groups in the datasets. This theory seems plausible as I get two bands when I aggregate the dataset also for years (2 unique in the mpg dataset).
ggplot(aggregate(hwy~cyl*year,mpg,"sum")) +
geom_bar(aes(x = as.factor(cyl), y = hwy), stat="identity")
But I thought ggplot2 does the aggregation automatically for me when I set stat to identity? This actually works directly in R-Studio. So maybe the problem has more to do with knitr?
I truly believe that I have not had the same problem in the past. Maybe something changed with the update? Actually all my colleagues (6 other Mac and Windows computers) have the same problem.
R version 3.4.0 (2017-04-21)
Platform: x86_64-w64-mingw32 / x64 (64-bit)
ggplot2: 2.2.1
knitr: 1.15.1
source to share
As noted in the comment, the file type for an image can affect how the graphic is displayed in the output pdf.
Using the provided snippet:
```{r, echo = F, fig.cap = "My plot"}
ggplot(mpg) + geom_bar(aes(x = as.factor(cyl), y = hwy), stat="identity")
```
The default dev
is pdf and the resulting pdf graphics are given in the post of the question:
If you explicitly use dev
to use like in the snippet below then a png will be generated and the image in the resulting pdf will be just as needed.
```{r, echo = F, fig.cap = "My plot", dev = "png"}
ggplot(mpg) + geom_bar(aes(x = as.factor(cyl), y = hwy), stat="identity")
```
source to share