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

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.

Related

Assign figure caption to html widget (vtree package) in R markdown output

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

Render interactive treemap with highchart in flexdashboard

I am using flexdashboard to generate a interactive treemap. But the plot doesn´t render properly.
My code and output are the following:
---
title: "flexdashboard: Shiny Embedding"
output:
flexdashboard::flex_dashboard:
social: menu
source_code: embed
runtime: shiny
---
```{r global, include=FALSE}
library(tidyverse)
library(highcharter)
library(treemap)
## generate a sample dataset
sample<-tbl_df(data.frame(c("City1","City2","City3","City1","City2","City3",
"City2","City3"),
c("A","B","C","D","D","A","A","B"),
c(12,14,15,12,12,14,8,10)))
colnames(sample)<-c("City","Country","Amount")
variable<-"City"
trmap<-function(variable)
{
d<- cbind(sample[,variable],sample[,"Amount"])
tm <- treemap(d, index = variable,
vSize = "Amount")
highchart() %>%
hc_title(text = paste("Treemap de", variable ),
style = list(fontSize = "15px")) %>%
hc_add_series_treemap(tm)
}
```
Column {.sidebar}
-------------------------------------------
```{r}
selectInput(inputId="variable",label="group by",choices=c("City","Country"))
```
Column
------------------------------------------
### Plot
```{r}
renderPlot(trmap(input$variable))
```
The output of this code is the next dashboard:
But the plot initially is dynamic, because it shows the numbers of amount when I put the cursor in the box of every city.
How to render properly the plot to get the dynamic plot that shows the numbers??

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.

Problems with simultaneous use Sankey and d3tree htmlwidgets on R Notebook?

I use R notebook for data analysis report.
I want to render Sankey and d3tree htmlwidgets on R notebook simultaneously.
I put snakey and then d3tree example code in r chunk, output is well printed on rstudio.
When I entered preview button, sankey output well appeared on html.
But, d3tree output doesn't render on html.
I tryed that put d3tree and then sankey. the result is that two of d3tree and sankey dosen't render on html.
what is the problem??
Can i solve these?
the example code like below
---
title: "test"
output: html_notebook
---
```{r, echo=FALSE}
library(networkD3)
library(treemap)
library(d3treeR)
```
```{r, echo=FALSE}
net_cycles <- list(
links = data.frame(
source = c(0,0,0,1,1,5),
target = c(1,2,3,4,5,0),
value = 10
),
nodes = data.frame(
name = letters[1:6]
)
)
```
```{r, echo=FALSE}
data(business)
business$employees.growth <- business$employees - business$employees.prev
tree <- treemap(business,
index=c("NACE1", "NACE2"),
vSize="employees",
vColor="employees.growth",
type="value",
palette="-RdGy",
range=c(-30000,30000))
```
```{r}
sankeyNetwork(
net_cycles$links,
net_cycles$nodes,
Value = "value"
)
d3tree2(
# Brewer's Red-White-Grey palette reversed with predefined range
tree
,rootname = "World"
)
```

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

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.

Resources