Unwanted stripes in ggplot2 bar chart when knitted to pdf - r

When knitting a simple bar chart to pdf, I get some unwanted stripes in my bars (see 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 stripes do not appear when I create the plot directly in R-Studio (see left side of the attached screenshot).
I found a way to remove these stripes by aggregating the data before:
ggplot(aggregate(hwy~cyl,mpg,"sum")) +
geom_bar(aes(x = as.factor(cyl), y = hwy), stat="identity")
So I understand that these stripes should be coming from stacking all the other groups in the datasets. This theory seems plausible, since I get two stripes when I aggregate the dataset also by years (2 uniques in mpg dataset).
ggplot(aggregate(hwy~cyl*year,mpg,"sum")) +
geom_bar(aes(x = as.factor(cyl), y = hwy), stat="identity")
But I thought that ggplot2 is automatically doing the aggregation for me when I set stat to identity? Actually it does work directly in R-Studio. So maybe the problem has more to do with knitr?
I do believe that I did not had this same issue in the past. So maybe something changed with an update? Actually all my colleagues (6 other mac and windows computers) have the exact 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

As noted in a comment, the file type for the graphic can influence the way the graphic renders in the output pdf.
Using the provided chunk:
```{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 graphic in the pdf is as shown in the question post:
If you are explicit on the dev to use, as in the chunk below, then a png will be generated and the image in the resulting pdf is as wanted.
```{r, echo = F, fig.cap = "My plot", dev = "png"}
ggplot(mpg) + geom_bar(aes(x = as.factor(cyl), y = hwy), stat="identity")
```

Related

Hover to show image or icon in ggplot2 (R markdown)

I am fascinated by dynamic or interactive ggplot graphs. I found some easy hover options with ggiraph at https://davidgohel.github.io/ggiraph/ Here is a MWE for R markdown:
---
title: "Hover"
author: "Author"
output: html_document
---
## Hover ggplot2
```{r, warning=FALSE, message=FALSE}
library(ggplot2)
library(ggiraph)
data <- mtcars
data$carname <- row.names(data)
gg_point = ggplot(data = data) +
geom_point_interactive(aes(x = wt, y = qsec, color = disp,
tooltip = carname, data_id = carname)) +
theme_minimal()
girafe(ggobj = gg_point)
```
Is there any possibility to show a small image or icon when hover over a datapoint in a ggplot in markdown? I wonder how and where I would store these images. I would like to give every data point a specific image. I am working on famous painters, i.e. assume that I have very few data points in a scatterplot. Thus when people hover on "The Scream", they should see a little version of https://en.wikipedia.org/wiki/List_of_most_expensive_paintings#/media/File:The_Scream_Pastel.jpg

RMarkdown not printing Chinese characters in graphs

---
title:
output:
pdf_document:
latex_engine: xelatex
fontsize: 11pt
#mainfont: Calibri
classoption: letter
geometry: left=0.5in, right=0.5in, top=0.6in, bottom=1.25in
subparagraph: yes
header-includes:
- \usepackage[UTF8]{ctex}
- \usepackage{setspace}
- \usepackage{tocloft}
- \usepackage{anyfontsize}
- \usepackage{fancyhdr}
- \usepackage{fontspec}
- \usepackage{sectsty}
- \sectionfont{\huge}
- \subsectionfont{\fontsize{14}{16.8}\selectfont}
- \pagestyle{fancy}
- \renewcommand{\headrulewidth}{0pt}
---
```{r}
library(ggplot2)
print("中文")
df <- data.frame(
gp = factor(rep(letters[1:3], each = 10)),
y = rnorm(30)
)
ds <- plyr::ddply(df, "gp", plyr::summarise, mean = mean(y), sd = sd(y))
# The summary data frame ds is used to plot larger red points on top
# of the raw data. Note that we don't need to supply `data` or `mapping`
# in each layer because the defaults from ggplot() are used.
ggplot(df, aes(gp, y)) +
geom_point() +
geom_point(data = ds, aes(y = mean), colour = 'red', size = 3) +
labs(x = "中文")
```
After knitting this file, it seems that the character encoding works fine for the print function, but the Chinese characters do not show up in graph labels, and I get errors on character conversions. I am a Mac user.
TL;DR: This doesn't appear to be a knitr/rmarkdown issue, but rather an issue related to both the font and the output device. I'm not sure of the cause, but the workaround below involves changing the output font (Batang worked for me) and the output device (pdf is the default, but changing to cairo_pdf or png both worked for me).
First, identify a font family for which R will render the characters properly. I'm not sure in general how to determine this without trial and error, but in the past I've found that the Symbola and Batang fonts often seem to work with non-English characters and various unicode symbols. You'll need to install the fonts on your computer if you don't have them, and you also might need to use the extrafont package to register the fonts in R. Then you can run the plot code in the console and see if the Chinese characters render properly.
With the Batang font, I found that I was able to output plots to the console with the Chinese characters rendered properly. However, the standard pdf device failed to render the characters, whether saving the plot to pdf interactively or when knitting. Instead I tried the cairo_pdf and png devices and these both worked. Here's example code (using the same yaml as in your question):
```{r, include=FALSE}
knitr::opts_chunk$set(echo=FALSE)
library(ggplot2)
```
```{r, dev="cairo_pdf"}
df <- data.frame(
gp = factor(rep(letters[1:3], each = 10)),
y = rnorm(30)
)
ds <- plyr::ddply(df, "gp", plyr::summarise, mean = mean(y), sd = sd(y))
ggplot(df, aes(gp, y)) +
geom_point() +
geom_point(data = ds, aes(y = mean), colour = 'red', size = 3) +
labs(x = "中文", title="cairo_pdf device") +
#theme(axis.title.x=element_text(family="Batang")) # To change font only for x-axis title
theme(text=element_text(family="Batang", size=15))
```
```{r, dev="png", dpi=400}
ggplot(df, aes(gp, y)) +
geom_point() +
geom_point(data = ds, aes(y = mean), colour = 'red', size = 3) +
labs(x = "中文", title="png device") +
theme(text=element_text(family="Batang", size=15))
```
And here's what the plots look like in the output document:

ggplot2/knitr: geom_col shows breaks in PDF but not in RStudio/HTML

When including a plot with geom_col in an R Markdown report knitted to pdf, the stacked breaks between observations are made visible as gray lines:
```{r}
library(ggplot2)
ggplot(data = midwest) +
geom_col(mapping = aes(x = state, y = poptotal))
```
But when I run the exact same code directly in R Studio (or knit to HTML), the columns are shown as solid:
Is there something special to do to make the different observations not be shown in a pdf (e.g., to make the pdf-knitted plot look like the HTML-knitted one)?
Did you Try using geom_bar() instead of geom_col(), because geom_col() was created afterwards, its basically geom_bar() only
```{r}
library(ggplot2)
ggplot(data = midwest) +
geom_bar(stat="identity",mapping = aes(x = state, y = poptotal))
```
It might work, try it and let me know
You can also set fill and check what happens
geom_bar(stat="identity",mapping = aes(x = state, y = poptotal,fill="gray60"))

R markdown linking to a figure

I am creating a report with multiple figures and tables. I'd like to refer to them in the accompanying text. I've tried the following:
---
title: "Test"
output:
pdf_document
---
Figure \ref{test} is a graph
```{r test, fig.cap="This is a graph"}
df <- data.frame(gp = factor(rep(letters[1:3], each = 10)),
y = rnorm(30))
ggplot(df, aes(x = gp, y = y)) +
geom_point()
```
This is text to follow the diagram
\pagebreak
This is another page but can still link to Figure \ref{test}
But the result is:
Figure ?? is a graph
...
This is another page but can still link to Figure ??
Is there a default way to do this in R markdown without having to write functions myself
I think I found an answer here- https://github.com/yihui/knitr/issues/323
Using this code seemed to provide the behavior I think you're looking for, if I'm understanding correctly.
---
title: "Test"
output:
pdf_document
---
Figure \ref{fig:plot} is a graph
```{r plot-ref, fig.cap = "This is a graph\\label{fig:plot}"}
library('ggplot2')
df <- data.frame(gp = factor(rep(letters[1:3], each = 10)),
y = rnorm(30))
ggplot(df, aes(x = gp, y = y)) +
geom_point()
```
This is text to follow the diagram
\pagebreak
This is another page but can still link to Figure \ref{fig:plot}

Running Plotly charts in Slidify or R markdown

I am trying to build R Markdown presentation document using plotly charts , but its not showing us charts in the browser . Code below :
========================================================
```{r,echo=false}
library(plotly)
p <- ggplot(data = diamonds, aes(x = cut, fill = clarity)) +
geom_bar(position = "dodge")
ggplotly(p)
```

Resources