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

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

Related

RMarkdown adjust height to keep bar spacing equal with plots in a loop in a single chunk

In the following RMarkdown, I would like to have each barplot print so that the text size and box width are the same in each plot, and the height adjusts accordingly.
What is happening is that in the plots with few bars the bars are extremely wide, and in the plots with many bars the bars are thin and the labels squished.
---
title: "chunk plot height"
number_sections: yes
output: html_notebook
---
# Load Libraries
\```{r}
library(tidyverse)
library(magrittr)
library(rmarkdown)
\```
# Set Knitr Options
\```{r}
knitr::opts_chunk$set(
echo=TRUE,
dpi=300,
fig.width=12
)
\```
# Plot
\```{r}
for (n in seq(10,50,10))
{
knitr::opts_chunk$set(out.height=n)
data = data.frame(
X=sapply(c(letters, LETTERS)[1:n], function(x) rep(x,3) %>% paste0(collapse=''), USE.NAMES = F),
Y=rnorm(n)
)
plt =
data %>%
ggplot(aes(x=X, y=Y)) +
geom_col(position=position_dodge(width=1, preserve='single')) +
coord_flip()
print(plt)
}
\```

Unwanted stripes in ggplot2 bar chart when knitted to pdf

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")
```

Scaling plotly figures in knitr Latex document

I'm trying to include a plotly chart into a Latex document with knitr. Since knitr includes the webshot package this works well. But if I want to resize my figure for the latex output, the figure environment gets bigger but the plotly chart is not scalled to the manually set figure width and height.
Specifing the webshot options like recommend here, did not work neither. Scaling a ggplot chart works well, but how can I get the same results for the plotly chart?
\documentclass{article}
\usepackage{cleveref}
<<setup, echo=FALSE, message = FALSE, warning = FALSE>>=
library(ggplot2)
library(plotly)
#
%Preamble
\title{GGplot vs. Plotly }
\author{authors}
\date{2016}
\begin{document}
\maketitle
\section{Comparison ggplot with plotly}
This document illustrate the difference between ggplot and plotly. The chart in (\Cref{fig:ggplot}) is well placed in the document, but the chart in (\Cref{fig:plotly}) is neither scalled to the figure width, nor positioned next to the label.
<<ggplot, fig.lp="fig:", fig.cap = 'This is rendered with ggplot()', echo=FALSE, fig.width = 10, fig.height = 6>>=
ggplot(midwest, aes(x = state, y = percollege, colour = state)) + geom_boxplot()
#
<<plotly, fig.lp="fig:", fig.cap = 'This is rendered with plotly()', echo=FALSE, fig.width = 10, fig.height = 6, screenshot.opts = list(delay = 2, cliprect = 'viewport')>>=
plot_ly(midwest, x = ~state, y = ~percollege, color = ~state, type = "box")
#
\end{document}
I saw that the graphic file figure/plotly-1.pdf (generated by knitr/webshot, and then loaded into latex) has two pages and the plotly object is somewhere in the upper left corner. I guess the margins included in the webshot figure are in fact the problem.
R 3.2.3
knitr 1.14
ggplot2 2.1.0
plotly 4.5.2

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}

Size of font in ggplot plot changes in relation to plot using knitr

I'm using knitr for the first time, and have a problem concering the font size in ggplot plots. This is an example plot:
d <- ggplot(diamonds, aes(x = cut, y = clarity))
d + stat_sum(aes(label=..n..),geom="text",size=8)
In knitr I have the same plot in a chunk in my R markdown:
---
title: "Untitled"
output: html_document
---
```{r, echo=FALSE}
library(ggplot2)
d <- ggplot(diamonds, aes(x = cut, y = clarity))
d + stat_sum(aes(label=..n..),geom="text",size=8)
```
The plot looks fine in RStudio or when saved with ggsave(). However the numbers in the plot in the resulting knitr html have a much larger font size, in total and relative to the plot size:
In this example it does not matter much, but in my data the numbers start to overlap each other / run out of their cells.
An added complication is that the plot is done by a package, so I can't easily change the size option in the stat_sum call.
Try adjusting fig.height and fig.width:
---
title: "Untitled"
output: html_document
---
```{r, echo=FALSE,fig.height=10,fig.width=10}
library(ggplot2)
d <- ggplot(diamonds, aes(x = cut, y = clarity))
d + stat_sum(aes(label=..n..),geom="text",size=8)
```
If you want don't want the figure to be as large, you can adjust out.height and out.width:
---
title: "Untitled"
output: html_document
---
```{r, echo=FALSE,fig.height=10,fig.width=10,out.height=600,out.width=600}
library(ggplot2)
d <- ggplot(diamonds, aes(x = cut, y = clarity))
d + stat_sum(aes(label=..n..),geom="text",size=8)
```

Resources