Shiny renderPlot within Interactive Document opens a new Browser Window with dygraph - r

I have the following RMarkdown .Rmd document. When you run the following, the sliderInput is "reactive" and adjust the smoothing appropriately; however, the plot keeps generating in a new separate browser window rather than within the document itself.
Any ideas why this is happening or how to fix this behavior?
---
title: "Untitled"
output: html_document
runtime: shiny
---
```{r echo=FALSE}
library(dygraphs)
sliderInput("span", label = "Select Span",
min=0.05, max=1, value=0.5, step=0.05)
renderPlot({
plx <- predict(loess(ldeaths ~ time(ldeaths), span=input$span), se =T)
fit <- plx$fit
lower <- plx$fit - qt(0.975, plx$df) * plx$se
upper <- plx$fit + qt(0.975, plx$df) * plx$se
all <- cbind(ldeaths, fit, lower, upper)
dygraph(all, main="Title") %>%
dySeries(c("lower", "fit", "upper"), label="Deaths")
})
```

Well, I'm an idiot, the answer is that there's already a renderDygraph() function within the dygraphs package!
I'm going to keep this open so maybe someone can explain to me what's going on behind the scenes that makes this work correctly and why you cannot use renderPlot() directly. I will try and remember to update this answer if I learn from looking through the source.

Related

How to display hundreds of plots neatly in Rmarkdown?

I have a loop code that generate 100 different plots from a subset of a data. The simplified version of the code is as follow:-
for (i in 1:100) {
df <- alldata[alldata$id==i,]
plot(df)
}
The problem is I need to use R markdown to display the results. However, in the above code, the 100 plots will be display one after another in long pages, which will be very untidy.
I would like to display one plot at a time, but allow the viewer to click on the 'next page' to see the next plot. Is it possible to do so in R markdown?
Thanks and sorry if my question is too easy, as I am completely new to this (first time coding).
You can try my approach. I used html_document and tabsets ... works fine for my needs.
---
title: "Plot in loops"
output: html_document
---
# Title {.tabset .tabset-fade}
```{r, results='asis'}
for (i in 1:100) {
df <- data.frame(
x = 1:100,
y = runif(100)
)
cat( paste('## title no.', i, '\n' ) )
plot(df)
cat('\n \n')
}
```

Shiny Parallel Coordinates with Brushing and Linking

I'm creating a flexdashboard / Shiny app in R using Rstudio and am trying to create a dashboard with two components: a parallel coordinates graph on top and a table below the graph.
I'm trying to use Brushing and Linking to select specific axis in the parallel coordinate graph to affect and filter data in the table.
Below is my code (adapted from https://jjallaire.shinyapps.io/shiny-ggplot2-brushing/):
---
title: "ggplot2 Brushing"
output:
flexdashboard::flex_dashboard:
orientation: columns
social: menu
source_code: embed
runtime: shiny
---
```{r global, include=FALSE}
# load data in 'global' chunk so it can be shared by all users of the dashboard
library(datasets)
mtcars2 <- mtcars[, c("mpg", "cyl", "wt")]
```
```{r}
# Reactive that returns the whole dataset if there is no brush
selectedData <- reactive({
data <- brushedPoints(mtcars2, input$plot1_brush)
if (nrow(data) == 0)
data <- mtcars2
data
})
```
Column {data-width=650}
-----------------------------------------------------------------------
### Miles Per Gallon vs. Weight {data-width=600}
```{r}
library(ggplot2)
library(GGally)
plotOutput("plot1", brush = brushOpts(id = "plot1_brush"))
output$plot1 <- renderPlot({
ggparcoord(mtcars2) + geom_line()
})
```
### Car Details {data-width=400}
```{r}
renderTable({
selectedData()
}, rownames = TRUE)
```
As you can see, brushing and linking are not working. What am I missing here? I've read a few questions about the topic and particularly around XY variables and only working for scatterplots, etc. But certainly there is a way around this and I can't seem to find a solution. Does anybody have an idea on how to make brushing and linking work with parallel coordinates in Shiny?
I have tried to find solution to Your problem but actually it is not possible at this moment to retrieve the data using brush from any parallel coordinates plot (neither plotly or ggplot2). You can easily use the brush in plotly, but You will not be able to get the data out of it (in Your case it is selectedData()). Maybe You should try another plot type.

How to embed an interactive shiny plot in a pdf / presentation? (via knitR maybe)

As the topic implies I am looking for a way to combine interactive shiny plots with knitr´s way of producing presentations/pdfs.
The following intuitive approach should make my idea comprehensible.
---
title: "Test"
runtime: shiny
output:
pdf_document
---
```{r}
library(shiny)
library(knitr)
library(rmarkdown)
sliderInput("bins",
"Choose Standard Deviation:",
min = 0,
max = 2,
value = 1,
step = 0.1)
sliderInput("length",
"Choose Length of Process:",
min = 100,
max = 10000,
value = 1000,
step = 100)
renderPlot({
#create a random walk
set.seed(12)
y <- cumsum(rnorm(input$length,0,input$bins))
plot(y, type="l")
})
```
I know it´s not a big deal to get that code into a html document, but is there a way to get the exact same thing (or at least close to that) in a pdf document?
So I want a pdf file with aN interactive plot. Is that somehow possible?
Many thanks in adavance :)
The comment from HubertL is basically the answer: it is not possible.

markdown+shiny+ggvis: graphics updated in new browser window

When using ggvis with shiny+markdown, everytime my graphic is updated, a new browser window is open.
Consider the following MWE:
---
title: "a"
author: "b"
date: "2015"
output: html_document
runtime: shiny
---
Works fine when using base graphics:
```{r,echo=FALSE}
X <- data.frame(t=1:50,x=arima.sim(list(1,0,0),50))
inputPanel(
sliderInput('p','p',0,2,0,1,TRUE),
sliderInput('n','n',0,1,0.5,0.1,TRUE)
)
renderPlot({
plot(X)
lines(predict(loess(x~t,X,span=input$n,degree=input$p),X$t),col='red')
})
```
When using ggvis, the graphic is updated in a new window!
```{r,echo=FALSE}
library(ggvis)
inputPanel(
sliderInput('p','p',0,2,0,1,TRUE),
sliderInput('n','n',0,1,0.5,0.1,TRUE)
)
renderPlot({
X %>% ggvis(x=~t,y=~x) %>% layer_points() %>%
layer_model_predictions(stroke:='red',model='loess',formula=x~t,
model_args=list(span=input$n,degree=input$p))
})
```
I found no updated example where the Shiny variable is accessed explicitly as in this MWE...
Reading through the Properties and scales vignette of ggvis, I now realize that it is easier to use their Shiny wrappers: input_slider instead of sliderInput.
So, the previous code would become:
```{r,echo=FALSE}
X %>% ggvis(x=~t,y=~x) %>% layer_points() %>%
layer_model_predictions(stroke='red',model='loess',formula=x~t,
model_args=list(
span=input_slider(0,2,1,1,TRUE),
degree=input_slider(0,1,0.01))
```
I could have used Shiny directly, but apparently, I would have to tell ggvis about shiny using bind_shiny, and tell shiny about ggvis using ggvisOutput.

2 Knitr/R Markdown/Rstudio issues: Highcharts and Morris.js

I'm presently trying to replicate a few different types of rCharts using my own data. The first is a HighCharts graph with the following code:
````{r}
setwd("C:/Users/ypetscher/Dropbox/R fun")
blah<-read.csv("g8a.csv")`
require(slidify)
require(rCharts)
require(rHighcharts)
```
```{r}
x<-data.frame(blah,stringsAsFactors=TRUE)
colnames(x)<-substr(colnames(x),2,5)
a<-rHighcharts:::Chart$new()
a$chart(type="column")
a$title(text="Percent of Students on Grade Level on G8 FCAT for Reading (1), Math (2), Writing (3), and Science (4)")
a$xAxis(categories=rownames(x))
a$yAxis(title=list(text="Percent Proficient"))
a$data(x)
```
When this is run as a chunk, the graph is produced nicely, but when I use Knit HTML in markdown, it sticks at the preview stage for a while and when I terminate it, it gives a "status 15" message, which I'm unclear what that means and how it should be resolved.
A second graph I'm trying is a Morris.js graph in Markdown with knitr. I took my R code and put into R Markdown which looks like:
```{r}
library(slidify)
library(knitr)
library(rCharts)
library(RColorBrewer)
library(reshape2)
setwd("C:/Users/ypetscher/Dropbox/R fun")
blah<-read.csv("g8.csv")
blah
```
```{r}
m2<-mPlot(x="year",y=colnames(blah)[-1],data=blah, type="Bar")
m2$set(barColors=brewer.pal(4,"Spectral"))
m2$set(xlab="Year")
m2$set(postUnits="%")
m2$set(hideHover="auto")
m2
```
When I run the chunks, it produces a nice graph the way I expected with an html file of (file:///C:/Users/ypetscher/AppData/Local/Temp/RtmpW4q3ka/filed284f137718.html); however, when I click on Knit HTML, I obtain a file which includes the code, but doesn't produce the graph. Additionally, when Google Chrome comes up I receive an error of :
"No webpage was found for the web address:
file:///C:/Users/YPETSC~1/AppData/Local/Temp/Rtmpk1Pfbp/filee0c383670e0.html
Error 6 (net::ERR_FILE_NOT_FOUND): The file or directory could not be
found."
Any help would be greatly appreciated in diagnosing these issues. Thank you much!
NOTE: This is the same solution I posted in the knitr google group.
To get rCharts to work with knit2html, you will need to use the print method with the argument include_assets = TRUE. This is because knitr will not add the js and css assets required by an rCharts plot automatically. Here is a minimal working example.
## MorrisJS with Knit2HTML
```{r results = 'asis', comment = NA}
require(rCharts)
data(economics, package = 'ggplot2')
econ <- transform(economics, date = as.character(date))
m1 <- mPlot(x = 'date', y = c('psavert', 'uempmed'), type = 'Line',
data = econ)
m1$set(pointSize = 0, lineWidth = 1)
m1$print('chart2', include_assets = TRUE)
```
Note that you need to use m1$print('chart2', include_assets = TRUE, cdn = TRUE) if you intend to publish your chart on RPubs, for otherwise the JS and CSS assets will be served from your local library.
Hope this helps.

Resources