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.
Related
Plot plotly heatmap on Rmarkdown. I want to display the DT of the clicked data by clicking the heatmap. It was possible with Shiny. Is it possible to reproduce this function with Rmarkdown? Thank you
rmarkdown.Rmd
```{r}
library(plotly); library(DT); library(shiny)
p <- plot_ly(data=iris, x=~Sepal.Length, y=~Sepal.Width, z=~Petal.Length, type="heatmap", source = "heat")
p
observeEvent(event_data("plotly_click", source = "heat"),{
x <- event_data("plotly_click", source = "heat")$x
iris_ <- filter(iris, Sepal.Length == x)
dt <- datatable(iris_)
})
dt
```
This is the only way I could get it to work, but hoping you can convert this into a heatmap. For me, the heatmap wasn't rendering properly. This example uses the crosstalk function and utilizes brushing and will auto render the DT table of the selected table.
```{r}
library(ggplot2)
library(plotly)
library(DT)
m<-highlight_key(iris)
p<-ggplot(m,aes(Sepal.Length,Sepal.Width))+geom_point(aes(color = Species))
gg<-highlight(ggplotly(p),"plotly_selected")
crosstalk::bscols(gg,DT::datatable(m))
```
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')
}
```
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,
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.
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.