Hello everyone reading this.
I am trying out R with knitr and rCharts to generate Rmd -> md -> html files with flashy plots. At the moment I am trying out nPlot wrapper and I cannot get addControls feature working for some reason. Here is my simple example:
```{r testing, include=T, results='asis', comment=NA, message=F, echo=F}
cData <- read.csv("~/USCrime2012.csv")
crimebarPlots = nPlot(ViolentCrime ~ State, data = cData, type = "discreteBarChart")
crimebarPlots$xAxis(rotateLabels = -90)
#crimebarPlots$addControls("y", value = "ViolentCrime", values = names(cData[,-1]))
crimebarPlots$print("test", include_assets=T, cdn=T)
```
Everything works while the commented line is left out, but once I include it the plot stops working - all I get is an empty drop-down list button with no labels.
I adopted this example from here: http://bl.ocks.org/patilv/raw/7968210/ where it's presented to be working fine. I got the data from HERE
Before doing this I tried to run it with my own dataset with the same kind of result.
Any help or suggestions greatly appreciated.
-KK.
Related
I'm trying to create an HTML Rmarkdown that runs many plotly graphs... The issues in the HTML file is too big and can't open it.
I found out that I can use "partial_bundle" function to reduce the size of my file. On my home computer it works great.
I created the following file:
```{r pressure, echo=FALSE, error=TRUE}
dta = data.frame(x= rnorm(1000), y = rnorm(1000))
plot_ly(dta, x=~x,y=~y)
```
Its size is ~5Mb and when I add the funtion "partial_bundle":
```{r pressure, echo=FALSE, error=TRUE}
dta = data.frame(x= rnorm(1000), y = rnorm(1000))
plot_ly(dta, x=~x,y=~y) %>%
partial_bundle()
```
The size reduces to ~2.5Mb which is great.
The issues is in my work environment, the function doesn't work because it seems like it needs to access a server that it's blocked in my work:
It there a way to use it offline? There is a description here of the function but I dont get how to use it offline on Rmarkdown..
Edit: My end goal is to know how use the js script on barchart plotlys... I need help implementing the js files in my rmarkdown...
I feel like I've gone down a rabbit hole when all I want is some nice tables in my pdf. Long story, here goes:
I want to print some tables to a PDF from r markdown. I usually use Kable and it works fine. That being said, this table is going to have some really long values, and an unknown number of columns that get generated, and I was having a hard time specifying which column would be what width when I didn't know yet in kable. Anyhow, that led me to flextable.
When I knit to html, the table looks great, like so:
But I'm having trouble knitting to pdf. I understand, via other stack answers, that flextable's need to be saved as images to be plotted to pdf. So I have code like this:
ft <- flextable(x)
ft <- autofit(ft)
tf <- tempfile(fileext = ".png")
## Not run:
if( require("webshot2") ){
save_as_image(x = ft, path = "myimage.png")
}
plot(tf)
But at first it gave me the error that I didn't have the webshot2 package, so after some trouble I installed that (it didn't line up with my version of R (I'm on rstudio.cloud) and then when I try to run it now, it says
Am I missing something obvious? How do I save a flextable as an image and then plot it in my pdf?
I've also tried Joanna's solution here: Is it possible to generate the RTable (FlexTable) in pdf with RMarkdown? and r tells me could not find function "as.html". Even though both flextable and htmltools have been loaded.
P.s. providing reproducible data would be very long given all the code that generates the tables and the fact I need it to knit into a pdf, will provide rstudio.cloud link if anyone is interested
You can now produce PDF without the need of webshot package (flextable >= 0.6.0):
---
title: "Untitled"
output:
pdf_document:
latex_engine: xelatex
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(flextable)
```
```{r}
ft <- flextable(head(airquality))
ft <- autofit(ft)
theme_vader(ft)
```
I am using R notebook. This is my chunk:
```{r}
test = matrix(rnorm(200), 20, 10)
pheatmap::pheatmap(test)
```
I guess it's due to the way pheatmap generates the plot, but it actually generates a blank plot first. Thus, this is the output I see:
How do I get rid of that first image? I see it in the RStudio output (screenshot above) and in the .nb.html file. If I knit to HTML, the blank plot is not there.
I tried different fig.keep options. They work when I knit to HTML, but they don't seem to have an effect in the .nb.html file. How can I get rid of it?
Update: This issue was fixed in pheatmap. It may still be applicable to other scenarios.
This is weird. Try this:
```{r}
library(pheatmap)
p <- pheatmap(test, silent = TRUE)
plot(p$gtable)
```
It produces exactly what you describe. Now, split it into two chunks.
```{r}
library(pheatmap)
p <- pheatmap(test, silent = TRUE)
```
```{r}
plot(p$gtable)
```
It works! I have no idea why, though.
I created a custom function which sets mfrow to nxn and creates n^2 scatter plots, with multiple data sets on each plot, based on an input list of data frames. The signature of my plotting function looks like this:
plot.return.list<-function(df.list,num.plot,title)
Where df.list is my list of data frames, num.plot is the total number of plots to generate (used to set mfrow) and title is the overall plot title (the function generates titles for each individual sub-graph).
This creats plots fine when I run the function from the console. However, I'm trying to get this figure into a markdown document using RStudio, like so:
```{r, fig.height=6,fig.width=6}
plot.return.list(f.1.list,4,bquote(atop("Numerical Approximations vs Exact Soltuions for "
,dot(x)==-1*x*(t))))
```
Since I haven't set the echo option in my {r} statement, this prints both the plotting code as well as the plot itself. However, if my first line instead reads:
{r, fig.height=6,fig.width=6,echo=FALSE}
Then both the code AND the plot disappear from the final document.
How do I make the plot appear WITHOUT the code? According to the example RStudio gives, setting echo=FALSE should make the plot appear without the code, but that isn't the behavior I'm observing.
EDIT: I seem to have tracked my problem down to kable. Whether or not I'm making a custom plot-helper function, any call to kable kills my plot. This can be reproduced in a markdown:
---
title: "repro"
author: "Frank Moore-Clingenpeel"
date: "October 9, 2016"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(knitr)
options(default=TRUE)
repro.df<-data.frame((0.1*1:10)%*%t(1:10))
```
```{r, echo=FALSE}
kable(repro.df)
```
```{r, fig.height=6,fig.width=6,echo=FALSE}
plot(repro.df[,1],repro.df[,2])
```
In this code, the plot won't plot because I have echo set to false; removing the flag makes the plot visible
Also note that in my repro code, kable produces a table with a bunch of garbage in the last line--I don't know why, but this isn't true for my full original code, and I don't think it's related to my problem.
Thanks for the reproducible example. From this I can see that the problem is you don't have a newline between your table chunk and your plot chunk.
If you were to knit this and examine the MD file produced by knit (or set html_document as your output format and have keep_md: true to look at it), you would see that the table code and plot code are not separated by any newline. Pandoc needs this to delimit the end of the table. Without it, it thinks your ![](path/to/image.png) is part of the table and hence puts it as a "junk line" in the table rather than an image on its own.
Just add a newline between the two chunks and you will be fine. (Tables need to be surrounded with blank lines).
(I know you are compiling to LaTeX so it may confuse you why I am talking about markdown. In case it does, when you do Rmd -> PDF, Rmarkdown uses knit to go from RMD to MD, and then pandoc to go from MD to tex. This is why you still need to make sure your markdown looks OK).
I'm writing an Rmd file, to be processed by knitr into HTML. It contains some R chunks that generate figures, which get stored as data URIs in HTML.
1) How do I add a caption to such an image? I'd like to have a caption that says something like "Figure 3: blah blah blah", where the "3" is automatically generated.
2) How do I later on reference this image, i.e., "as you can see in Figure 3, blah blah".
I'm late to the party, but I wanted to mention a small package I recently built to do figure captioning and cross-referencing with knitr. It is called kfigr and you can install it using devtools::install_github('mkoohafkan/kfigr'). It is still in active development but the main functionality is there. Be sure to check out the vignette, it shows some usage examples and defines some hooks for figure captions and anchors (I may later choose to have the package import knitr and define those hooks on load).
EDIT: kfigr is now available on CRAN!
You can create the figure numbers with a simple counter in R; see one example here. The problem is whether the markdown renderer will render the figure caption for you: R Markdown v1 won't, but v2 (based on Pandoc) will.
I do not know. There is no direct way to insert a label as an identifier for figures, so it is probably not possible to cross reference figures with pure Markdown. Once you've got issues like this, think (1) do I really need it? (2) if it is intended to be a document with a complicated structure, I think it is better to use LaTeX directly (Rnw documents).
Also very late to the party I changed Yihuis suggestion here that he also linked above to do referencing.
```{r functions, include=FALSE}
# A function for captioning and referencing images
fig <- local({
i <- 0
ref <- list()
list(
cap=function(refName, text) {
i <<- i + 1
ref[[refName]] <<- i
paste("Figure ", i, ": ", text, sep="")
},
ref=function(refName) {
ref[[refName]]
})
})
```
```{r cars, echo=FALSE, fig.cap=fig$cap("cars", "Here you see some interesting stuff about cars and such.")}
plot(cars)
```
What you always wanted to know about cars is shown in figure `r fig$ref("cars")`
One way to do both of these is described here: http://rmflight.github.io/posts/2012/10/papersinRmd.html
Another is described here (but I don't know if it does your #2). http://gforge.se/2014/01/fast-track-publishing-using-knitr-part-iii/
Another solution:
https://github.com/adletaw/captioner
From the README:
captioner() returns a captioner function for each set of figures, tables, etc. that you want to create. See the help files for more details.
For example:
> fig_nums <- captioner()
> fig_nums("my_pretty_figure", "my pretty figure's caption")
"Figure 1: my pretty figure's caption"
> fig_nums("my_pretty_figure", cite = TRUE)
I did both (figure numbers + references) with bookdown. I added in output section in the header of the file:
output:
bookdown::html_document2:
fig_caption : TRUE
Then I created a figure in a R code chunk like follows:
{r, my-fig-label,echo=F, eval=T, fig.align = 'center', fig.cap="This is my caption"}
knitr::include_graphics(here::here("images", "my_image.png"))
This produces an automatic number under your figure. You can refer to it with \#ref(fig:my-fig-label).
Using the official bookdown documentation 4.10 Numbered figure captions:
---
output: bookdown::html_document2
---
```{r cars, fig.cap = "An amazing plot"}
plot(cars)
```
```{r mtcars, fig.cap = "Another amazing plot"}
plot(mpg ~ hp, mtcars)
```