I wonder if I can use ggvis in .Rnw with knitr. I tried the following code in RStudio Version 0.98.1091. But it is not working.
\documentclass{book}
\usepackage[T1]{fontenc}
\usepackage{float}
\usepackage{booktabs}
\usepackage{dcolumn}
\usepackage{geometry}
\geometry{verbose,tmargin=2cm,bmargin=2cm,lmargin=2cm,rmargin=2cm}
\begin{document}
\chapter{Test}
\begin{figure}[H]
<< label = Plot1, fig.lp = "Plot1", fig.cap = "Test Plot" >>=
library(ggvis)
p <- mtcars %>% ggvis(x = ~wt, y = ~mpg) %>% layer_points()
print(p) # Commenting this line will compile the document
#
\end{figure}
\end{document}
It throws the following error:
LaTeX errors:
! Missing $ inserted.
<inserted text>
$
l.70 \end{kframe}<!--html_
preserve--><div id="plot_id298740869-container" cl...
! Please use \mathaccent for accents in math mode.
Edited
Commenting the line print(p) will compile the document without any error.
Would be sufficient if there is a command like ggsave() to save the ggvis plots.
Yes.
The export_png function can create a PNG image from a ggvis object.
It uses the node javascript interpreter, and node needs the vega package installed.
At the linux command line, I can do this with:
sudo npm -g install vega
to install the vega package globally using the node package manager. I don't know how you do this on a Windows or Mac box.
Once that's done, you can:
\documentclass{book}
\usepackage[T1]{fontenc}
\usepackage{float}
\usepackage{booktabs}
\usepackage{dcolumn}
\usepackage{geometry}
\geometry{verbose,tmargin=2cm,bmargin=2cm,lmargin=2cm,rmargin=2cm}
\begin{document}
\chapter{Test}
\begin{figure}[H]
<< label = Plot1, fig.lp = "Plot1", fig.cap = "Test Plot" >>=
library(ggvis)
p <- mtcars %>% ggvis(x = ~wt, y = ~mpg) %>% layer_points()
export_png(p,"Plot1.png")
#
\includegraphics[width=0.8\textwidth]{Plot1.png}
\end{figure}
\end{document}
do: knit2pdf("gg.Rnw")
and get:
Note you'll have to add captions and labels manually. Perhaps Yihui can be persuaded to integrate this better into knitr, or there may be a way using some of the knitr hooks. Anyway, concept proved...
Related
The following is the minimal reproducing example, if you use debian system, one can install octave by snap or apt easily.
\documentclass[english]{article}
\title{Minimal example of octave with knitr for Rnw file}
\author{Xudong Sun}
\begin{document}
\maketitle
<<engine='octave', engine.path='/snap/bin/octave', results='markup', echo=TRUE, out.width=5>>=
x = -10:0.01:10
#
\end{document}
The output text runs out of margin:
Any solutions?
You can simply add the white background ;)
F.e.:
\documentclass[english]{article}
\title{Minimal example of octave with knitr for Rnw file}
\author{Xudong Sun}
\begin{document}
\maketitle
<<chunkName, echo=FALSE, comment=NA, background='#FFFFFF'>>=
x <- rnorm(100)
x
#
\end{document}
... but if you want to save "default dimensions of the bg area" you can use f.e:
<<chunkName, echo=FALSE, comment=NA, background='#FFFF33'>>=
options(width = 60)
x <- rnorm(100)
x
#
I need to implement a figure caption in a plot that is generated by the vtree package in R markdown. I learned that this is a htmlwidget and figure captions should now be possible for htmlwidgets used in R markdown with install.packages('webshot') and webshot::install_phantomjs() (reference: https://bookdown.org/yihui/bookdown/html-widgets.html#ref-R-DT.
But days after I am not really any step further. I did not find any example (show case) for this issue (fig.cap for htmlwidgets in R markdown in the net) so my hope is that someone out there can give me some help!
In my iris dataset example, in Fig. 1 the caption is not working in contrast to Fig. 2.
my iris set example RMD file:
YAML
---
title: "test"
author: "TJ"
date: "14 12 2020"
output: html_document
---
code chunk 1: load libraries and data
knitr::opts_chunk$set(echo = TRUE)
library(vtree)
library(webshot)
library(tidyverse)
attach(iris)
df <- iris %>%
select(Species) %>%
cbind(sapply(levels(.$Species), `==`, .$Species))
code chunk 2: Figure 1
{r fig1, echo=FALSE, fig.cap="Vtree plot"}
vtree(iris, "Species")
code chunk 3: Figure 2
{r fig2, echo=FALSE, fig.cap="Scatter plot iris dataset"}
plot(Sepal.Length, Sepal.Width, main="Scatterplot Example",
xlab="Sepal Length ", ylab="Sepal Width ", pch=19)
There is a workaround using the Magick package.You save the image as .png using grVizToPNG (make sure you comment this line out before you render your document or put it in a separate chunk with ยด{r eval = FALSE}, otherwise you will get an error during rendering:
```{r eval=FALSE, echo = FALSE}
myimage <- vtree(iris, "Species")
saveMyimage <- grVizToPNG(myimage, width=800)
```
Here you use the Magickpackage:
```{r magick, echo= FALSE}
MyimagePNG <- image_read("myimage.png")
image_annotate(MyimagePNG, "Vtree plot", size = 35, gravity = "southwest")
```
How can I add a figure note right below the image in bookdown::pdf_document2? It is relatively easy to do for plots that created by ggplot2. grid.arrange can do the work with grid.arrange(<plot>, bottom = <figure_notes>). But if I insert an image manually, e.g., knitr::include_graphics(rep("images/knit-logo.png", 3)), is there a way to add a figure note to it? I saw a knitr option, fig.subcap. But this fails to compile:
```{r fig.show="hold", fig.cap = "a", fig.subcap = "b"}
knitr::include_graphics(rep("images/knit-logo.png", 3))
```
This returns:
This is pdfTeX, Version 3.14159265-2.6-1.40.18 (MiKTeX 2.9.6350 64-bit)
entering extended mode
! Undefined control sequence.
<recently read> \subfloat
Error: Failed to compile miniSample.tex. See miniSample.log for more info.
Thanks
If you want to use subfigures, you have to load the subfig package within LaTeX. This can be done by using the header-includes argument in the YAML, as explained here.
Here is a minimal, reproducible example, It creates a local image "temp.jpg" and then produces three subfigures:
---
output: pdf_document
header-includes:
- \usepackage{subfig}
---
```{r}
jpeg(filename = "temp.jpg")
plot(cars)
dev.off()
```
```{r fig.show="hold", fig.cap = "a", fig.subcap = c("Your Caption", "Another Caption", "Isn't this great"), fig.ncol = 3, out.width="33%"}
knitr::include_graphics(rep("temp.jpg", 3))
```
Check out this post for the original description: Subfigures or Subcaptions with knitr?
Found an expedient solution:
Read the image into R using magick::image_read;
Convert the image to raster project with rasterGrob;
Create a note with textGrob; Use grid.arrange to present;
Present the image together with note using grid.arrange.
plot_A <- magick::image_read(<path>) %>% rasterGrob(interpolate = TRUE)
note <- textGrob("This is a note.")
grid.arrange(plot_A, bottom = note)
I'm unable to convert charts created by plotly in R sweave to Pdf. But other charts can be created. Is there any other additional code needs to be added for plotly charts?
Below is an example
\documentclass{article}
\begin{document}
\SweaveOpts{concordance=TRUE}
<<echo = FALSE>>=
C1<-c("A","B","C")
C2<-c(10,20,30)
Df<-data.frame(C1,C2)
#
\begin {figure}
<<echo = FALSE, fig = TRUE>>=
suppressWarnings (library (plotly))
plot_ly(Df, x = ~C1, y = ~C2, type = "bar")%>% layout(title = "ABC")
#
\caption {PlotlyChart}
\end {figure}
Normal Chart
\begin {figure}
<<echo = FALSE, fig = TRUE>>=
barplot(Df[ ,2], names.arg = Df[ ,1])
#
\caption {Normal_Chart}
\end {figure}
\end{document}
When I try a normal box plot in R, it works. Only when I add Plotly chart, I get an error message as
Running pdflatex on ABC.tex...failed
Error running /Library/TeX/texbin/pdflatex (exit code 1)
I'm new to R sweave and Latex, so any help is appreciated. Thanks!
Plotly produces javascript code that draws the plot. This code is to be executed within a web browser. Plotly is usable when generating an HTML document only. No PDF, no Latex.
BUT you can use package webshot with phantomjs to save the plotly as an image, then include the image as a figure.
First install webshot:
install.packages("webshot")
webshot::install_phantomjs()
Then modify you Sweave file like this:
\documentclass{article}
\begin{document}
\SweaveOpts{concordance=TRUE}
<<echo = FALSE>>=
C1<-c("A","B","C")
C2<-c(10,20,30)
Df<-data.frame(C1,C2)
#
<<echo = FALSE, fig = FALSE>>=
suppressWarnings (library (webshot))
suppressWarnings (library (plotly))
py <- plot_ly(Df, x = ~C1, y = ~C2, type = "bar")%>% layout(title = "ABC")
export(py, file = "myplot.png")
#
\begin {figure}
\includegraphics{myplot.png}
\end {figure}
\end{document}
I'm currently using R's ggplot2 and tikzDevice packages to produce graphics and introduce them in LaTeX documents, but I'm struggling with the resulting big white spaces between the figures and the captions, as you can see if you compare the images (I've manually highlighted the spaces to make it clearer):
Here's my MWE:
The R code:
library(ggplot2)
library(tikzDevice)
set.seed(1)
x <- rnorm(200)
tikz(file = "Rplots.tex", width = 4, height = 4)
qplot(x, geom = "histogram")
dev.off()
and the LaTeX code:
\documentclass{article}
\usepackage{tikz}
\begin{document}
\begin{figure}
\centering
\include{Rplots}
\caption{\texttt{ggplot2} plot.}
\end{figure}
\begin{figure}
\centering
\begin{tikzpicture}[scale=3]
\clip (-0.1,-0.2)
rectangle (1.8,1.2);
\draw[step=.25cm,gray,very thin]
(-1.4,-1.4) grid (3.4,3.4);
\draw (-1.5,0) -- (2.5,0);
\draw (0,-1.5) -- (0,1.5);
\draw (0,0) circle (1cm);
\filldraw[fill=green!20!white,
draw=green!50!black]
(0,0) -- (3mm,0mm)
arc (0:30:3mm) -- cycle;
\end{tikzpicture}
\caption{\texttt{tikz} plot.}
\end{figure}
\end{document}
I'd like to know how to get rid of the great space between the caption and the figure via ggplot2.
PS. R version: 3.2.3, ggplot2 version: 2.1.0, tikzDevice version: 0.10-1. I've taken the code for the second plot from Tobias Oetiker's The Not so Short Introduction to LaTeX 2e, version 5.05, page 116.
It's been so long since I asked this question, but I wanted to answer what was the problem in the end.
As you can see in this question on the differences between \input{} and \include{}, the problem has to do with the fact that \include{} does a \clearpage before and after \include{}, that generates the white space I was talking about.
On the other hand, using \input{} is the equivalent to copy and pasting the code into the LaTeX document, that will prevent the white spaces.
it sounds more like a LaTeX question; I think the standard way to tweak the space is to set \abovecaptionskip
\documentclass{article}
\usepackage{tikz}
\setlength{\abovecaptionskip}{-15pt}
\begin{document}
\begin{figure}
\centering
\include{Rplots}
\caption{\texttt{ggplot2} plot.}
\end{figure}
\end{document}
I still don't get your problem, but let me suggest this complete example showing the exact same spacing for the tikz and standard pdf device when used in a knitr document.
---
title: "Untitled"
header-includes:
- \usepackage{caption}
output:
pdf_document:
fig_caption: yes
---
First, we try this
```{r pdf, echo=FALSE, dev='pdf', fig.height=2, fig.width=2, fig.cap='This is a standard graphic.'}
library(ggplot2)
ggplot() + theme(plot.background=element_rect(colour = "red"))
```
Next, we try this
```{r tikz, echo=FALSE, dev='tikz', fig.height=2, fig.width=2, fig.cap='This is a tikz graphic.'}
ggplot() + theme(plot.background=element_rect(colour = "red"))
```
\newpage
## Fixing space
\captionsetup{skip=0pt}
```{r pdf2, echo=FALSE, dev='pdf', fig.height=2, fig.width=2, fig.cap='This is a standard graphic.'}
library(ggplot2)
ggplot() + theme(plot.background=element_rect(colour = "red"))
```
```{r tikz2, echo=FALSE, dev='tikz', fig.height=2, fig.width=2, fig.cap='This is a tikz graphic.'}
ggplot() + theme(plot.background=element_rect(colour = "red"))
```