我正在尝试创建一个Flexdashboard,该Flexdashboard使用Leaflet中的事件(map_marker_click)在同一页的另一个图表中显示highcharts柱形图。我从其他示例中获取了信息,但在Flexdashboards教程或示例中找不到我要找的东西。 This非常接近我想要的内容,没有 Shiny 的输入或plot.ly集成,并且使用标记而不是多边形(进行的次数更少)。
我在R中的flexdashboard有以下代码:
title: "Flexdashboards and Leaflet"
output:
flexdashboard::flex_dashboard:
vertical_layout: fill
runtime: shiny
---
```{r,include=FALSE}
library(flexdashboard)
library(shiny)
library(leaflet)
library(highcharter)
```
```{r,include=FALSE}
latitude<-c(35.94077, 35.83770, 35.84545, 35.81584, 35.79387, 36.05600)
longitude<-c(-78.58010, -78.78084, -78.72444, -78.62568, -78.64262,-78.67600)
amounts1<-c(27, 44, 34, 46, 25, 15)
amounts2<-c(34, 52, 35, 78, 14, 24)
ids<-c("a", "b", "c", "d", "e", "f")
df<-data.frame(ids,amounts1,amounts2,latitude,longitude)
renderLeaflet({
leaflet() %>%
addTiles() %>%
addMarkers(lng=c(longitude),lat=c(latitude))
})
observeEvent(input$map_marker_click,{
click<-input$map_marker_click
if(is.null(click))
return()
})
```
```{r}
renderHighchart({
highchart() %>%
hc_chart(type = 'column')%>%
hc_add_series(name=amounts1, data=click())
hc_add_series(name=amounts2, data=click())
})
```
我想知道是否可以在带有或不带有 Shiny 集成的flexdashboard中完成。
最佳答案
下面的代码将完成它。简而言之,关键步骤是:
layerId
。这样,Leaflet将知道在指定事件时要返回哪些值。 eventReactive
,该layerId
返回该layerId
的值。然后,您可以根据需要使用它来对数据进行子集传递到图表。 renderHighchart
创建一个 react 性数据框架,该数据框架是主数据框架的子集。您可以在不执行此操作的情况下编写该应用程序,但是我想尽可能地将Shiny应用程序分解为多个组件。 希望这可以帮助!
---
title: "Flex Dashboard"
output:
flexdashboard::flex_dashboard:
orientation: columns
vertical_layout: fill
runtime: shiny
---
```{r setup, include=FALSE}
library(flexdashboard)
library(shiny)
library(leaflet)
library(highcharter)
latitude<-c(35.94077, 35.83770, 35.84545, 35.81584, 35.79387, 36.05600)
longitude<-c(-78.58010, -78.78084, -78.72444, -78.62568, -78.64262,-78.67600)
amounts1<-c(27, 44, 34, 46, 25, 15)
amounts2<-c(34, 52, 35, 78, 14, 24)
ids<-c("a", "b", "c", "d", "e", "f")
df<-data.frame(ids,amounts1,amounts2,latitude,longitude)
```
Column {data-width=650}
-----------------------------------------------------------------------
```{r}
output$map <- renderLeaflet({
leaflet() %>%
addTiles() %>%
addMarkers(data = df, lng = longitude, lat = latitude,
layerId = ~ids)
})
leafletOutput('map')
```
Column {data-width=350}
-----------------------------------------------------------------------
```{r}
click_marker <- eventReactive(input$map_marker_click, {
x <- input$map_marker_click
return(x$id)
})
data_for_chart <- reactive({
return(df[df$ids == click_marker(), ])
})
output$chart <- renderHighchart({
highchart() %>%
hc_chart(type = 'column') %>%
hc_add_series(data = c(data_for_chart()$amounts1,
data_for_chart()$amounts2))
})
highchartOutput('chart')
```