Synchronized interactivity between two R plots (plotly and leaflet) - r

I’d like to synchronize the interactivity of two R plots: a plotly plot and a leaflet map. The plotly plot graphs a time series for a specific location in the leaflet map. In other words, I’d like to select a location (or group of locations) in a map and see the corresponding selection in the ploty plot and vice versa select a time series in the plotly plot and see the corresponding marker in the map highlighted. So, in both directions.
The attached file (dataset1) is a R list that contains all data. Each element of the list is a dataset (time series) for each location. The linked variable for both plots is “Codi.Estació”.
I’ve tried the crosstalk package but the authors warn that “Crosstalk currently only works for linked brushing and filtering of views that show individual data points, not aggregate or summary views”. I’m not interested in an individual data point but a whole time series.
Could anyone help me how to handle that? Tips, examples, other packages (instead of leaflet) are welcome?
Thank you very much and have a nice summer,
Download the dataset: https://drive.google.com/file/d/1PkPm1ObcEer8Lne5vJMZR6MdFTONRSvY/view?usp=sharing
Download HTML output: https://drive.google.com/open?id=1YHko4V-iAUZqZr3wNC7zGEdrMhjmykSA
The code in R Markdown (*.Rmd) (to run in Rstudio):
---
title: "Piezometers La Bisbal del Penedès "
author: "J.M. Campanera"
output:
flexdashboard::flex_dashboard:
orientation: columns
social: menu
---
```{r setup, include = FALSE}
library(plotly)
library(leaflet)
library(flexdashboard)
load("dataset1.RData")
```
Column {data-width=700}
-----------------------------------------------------------------------
### Water depth
```{r echo=FALSE}
# Plot 1
p<-plot_ly()
for (i in 1:length(dataset1)) {
p<-add_trace(p,name=dataset1[[i]]$Codi.Estació[1],x=dataset1[[i]]$Data,y=dataset1[[i]]$Valor,mode = 'scatter',type="scatter")
}
p
```
Column {data-width=300}
-----------------------------------------------------------------------
### well locations
```{r echo=FALSE}
m <- leaflet()
m<-addTiles(m)
for (i in 1:length(dataset1)) {
m<-addCircleMarkers(m,lng=dataset1[[i]]$Longitud[1], lat=dataset1[[i]]$Latitud[1],label=dataset1[[i]]$Codi.Estació[1],labelOptions = labelOptions(noHide = T, textOnly = TRUE),popup=as.character(dataset1[[i]]$Fondària.Pou..m.[1]))
}
m
```

Finally I develop a solution:
1) Interactivity in Plotly plot and highlighting in the leaflet map:
I used the funtion "event_data(event=c("plotly_click"))" and I get the inspiration from
https://plot.ly/r/shinyapp-plotly-events/
2) Interactivity in Leaflet map and highlighting in the plotly plot:
I used the funtion "input$map_marker_click" and I get the inspiration from here: https://rstudio.github.io/leaflet/shiny.html
Thank you,

Related

R Flexdashboard multiple plots sizing

I just recently upgraded to R version 4.1.1 (from 3.6.3) and I noticed the following weird behaviour of flexdashboard:
I have a dashboard, where I plot multiple ggplots on one page (this number changes, so i do this with a loop), similarly as in the reproducible example below.
---
title: "My Reproducible Example"
output:
flexdashboard::flex_dashboard:
orientation: rows
vertical_layout: scroll
---
```{r }
library(ggplot2)
data("mtcars")
plots <- list()
for (i in 1:(ncol(mtcars) - 1)){
plots[[i]] <- ggplot(data = mtcars) +
geom_point(aes_q(x = as.name(names(mtcars)[1]),
y = as.name(names(mtcars)[1+i])))
}
for (i in 1:length(plots)){
print(plots[[i]])
}
```
When I run this with version 3.6.3 all of these plots are the same size. However, when I run this with version 4.1.1, I get one big plot, then a small plot, a big plot and a small plot, etc.
Is it also possible to create identically sized plots with a loop like this with R version 4.1.1?

How do I stop a chart from showing on R markdown?

Aims
I have got the ouput that I want i.e. an interactive tree map. Yet, the R Markdown output also shows the static tree map, which I do not want to include.
I also want to adjust the font size on the interactive chart. I know how to adjust the font sizes of the labels in the static diagram using "fontsize.labels", but this does not affect the interactive tree map.
Reprex
---
title: "Untitled"
date: "03/05/2021"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r pressure, echo=FALSE}
library(treemap)
library(d3treeR)
# dataset
group <- c(rep("group-1",4),rep("group-2",2),rep("group-3",3))
subgroup <- paste("subgroup" , c(1,2,3,4,1,2,1,2,3), sep="-")
value <- c(13,5,22,12,11,7,3,1,23)
data <- data.frame(group,subgroup,value)
# basic treemap
p <- treemap(data,
index=c("group","subgroup"),
vSize="value",
type="index",
palette = "Set2",
bg.labels=c("white"),
align.labels=list(
c("center", "center"),
c("right", "bottom")
)
)
# make it interactive ("rootname" becomes the title of the plot):
inter <- d3tree2( p , rootname = "General" )
inter
Output
How do I get rid of the top static tree map?
How do I increase the font size in the interactive tree map?
If you can only answer one of the questions, please do.

R Markdown flexdashboard output not producing ggplotly graphs

Please help regarding one issue that I have with the output I am getting with R Markdown-flexdashboard. I suppose I am doing something wrong.
I am using the following code in Rmarkdown:
title: "Economy and Population in Croatia 2000-2017"
output:
flexdashboard::flex_dashboard:
orientation: columns
vertical_layout: fill
library(flexdashboard)
library(tidyverse)
library(plotly)
library(ggrepel)
library(reshape2)
library(viridis)
library(DT)
load("my_work_space.RData")
Page 1 - National level
Column {data-width=600, .tabset}
Croatia 2000-2017: Population and Economy
g1
Croatia by County: Population 2018
ggplotly(g4)
Croatia by County: Economy 2017
ggplotly(g5)
Column {data-width=400}
Croatia: Economy and Demography by County
datatable(data = Datatable_Demo_Econs,
rownames=FALSE,
options=list(pageLength=3))
GDP of Regions 2000-2017
ggplotly(g2, tooltip = c("Region", "Year"))
Here are the pics of the code in the Rmarkdown code-pic1, code-pic2
However, I only manage to create the first plotly plot (g1) in the flexdashboard. Other graphs are produced via ggplotly (maybe that is the problem?). It looks like some kind of bug for ggplotly graphs in flexdash Rmarkdown script, or I am doing something wrong.
I am attaching the picture to see the almost empty flexdashboard.
Empty flexdashboard
It is confusing for me that exactly the same code produced the correct and full flexdashboard if I am using RStudio Cloud. I am attaching two pictures of correct and full dashboard produced in RStudio Cloud:
1. pic: correct flexdash
2. pic: correct flexdash
Thanks

Remove progress bar from knitr output

I'm analyzing some data and would like to do a Simpsons paradox on R. I've installed the Simpsons package and loaded the library. Here is an example based on the package documentation:
---
output: html_document
---
```{r}
library(Simpsons)
#generating data
Coffee1=rnorm(100,100,15)
Neuroticism1=(Coffee1*.8)+rnorm(100,15,8)
g1=cbind(Coffee1, Neuroticism1)
Coffee2=rnorm(100,170,15)
Neuroticism2=(300-(Coffee2*.8)+rnorm(100,15,8))
g2=cbind(Coffee2, Neuroticism2)
Coffee3=rnorm(100,140,15)
Neuroticism3=(200-(Coffee3*.8)+rnorm(100,15,8))
g3=cbind(Coffee3, Neuroticism3)
data2=data.frame(rbind(g1,g2,g3))
colnames(data2) <- c("Coffee","Neuroticism")
example <- Simpsons(Coffee,Neuroticism,data=data2)
plot(example)
```
This is returning a plot with 3 clusters (exactly what I need). However, when I Knit the Rmd file to HTML, I'm getting a lot of equals signs (======) with a percentage next to it like a loading grid which I would like to remove from my final output.
You can suppress any output messages in R by setting the knitr chunk option. If we wish to hide all code output other than plots, we can use the following solution:
---
output: html_document
---
```{r echo=FALSE, results='hide', fig.keep='all', message = FALSE}
library(Simpsons)
#generating data
Coffee1=rnorm(100,100,15)
Neuroticism1=(Coffee1*.8)+rnorm(100,15,8)
g1=cbind(Coffee1, Neuroticism1)
Coffee2=rnorm(100,170,15)
Neuroticism2=(300-(Coffee2*.8)+rnorm(100,15,8))
g2=cbind(Coffee2, Neuroticism2)
Coffee3=rnorm(100,140,15)
Neuroticism3=(200-(Coffee3*.8)+rnorm(100,15,8))
g3=cbind(Coffee3, Neuroticism3)
data2=data.frame(rbind(g1,g2,g3))
colnames(data2) <- c("Coffee","Neuroticism")
example <- Simpsons(Coffee,Neuroticism,data=data2)
plot(example)
```
I would note that this package seems to print out a lot more content that most packages, and therefore the combination of options are quite long.
An easier method would probably be to move the plot to a separate chunk and have all the analysis run before it. The include argument can be used to suppress all outputs, but this includes plots, hence why we must use two chunks:
```{r, include = FALSE}
# your code to build model
```
```{r}
plot(example)
```
Check out the full list of knitr chunk options here

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.

Resources