【问题标题】:Table not loading on click event in R shiny表未加载 R 闪亮中的点击事件
【发布时间】:2020-08-09 09:25:32
【问题描述】:

我正在使用 plotly 和 r shiny 在地图上绘制国家。我希望在地图上单击国家/地区时,包含有关国家/地区的行的数据子集以数据表的形式出现。但我无法实现它。我得到了表格,但表格中没有显示数据。任何帮助将不胜感激!

Mapbox_Token= 'Mapbox token'

library(plotly)
library("readxl")
library(dplyr)
library(readxl)
library(writexl)
library(shiny)
library(htmlwidgets)


data_1<- read.csv(".file.csv")
print(data_1)
library(formattable)

Sys.setenv("MAPBOX_TOKEN" = Mapbox_Token) # for Orca

ui <- fluidPage(
         
 plotlyOutput(outputId = "Plot"),
 DT::dataTableOutput('click')

)

server <- function(input, output,session) {

 output$Plot <- renderPlotly({
   df=read.csv("file2.csv")
   render_value(data_1)
   fig <- df%>% plot_mapbox(lat = ~lat, lon = ~lng,split = ~Country, 
size=0, type= 'scattermapbox',mode='markers',hoverinfo="none",showlegend=F,source='subset'
) 
fig <- fig %>% layout(title = 'No Of Companies',font= 
list(color='white'),plot_bgcolor = '#191A1A', paper_bgcolor = 
'#191A1A',mapbox = list(style = 'dark'),legend = list(orientation ='v',font = list(size = 6)),margin = list(l = 25, r = 25,b = 75, t = 25,pad = 
2))
fig<-fig %>% add_annotations(text ='Map shows number of 
companies by country. The size of the circles correspond to 
the number of 
companies.',x=0.5,y=-0.2,showarrow=FALSE,font=list(color='red'))
fig<- fig %>% add_markers(text = ~paste(paste('Country:',Country), 
paste("Number of Companies:",Name ), paste("Dataset:", Url),sep = " 
<br />"), size=~Name, hoverinfo = "text",marker=list(sizeref=0.1, 
sizemode="area"),showlegend=T)%>% 
onRender(fig, "function(el) {el.on('plotly_click', function(d) {var 
url = d.points[0].customdata;window.open(url);});}")

fig <- fig %>% config(mapboxAccessToken = Sys.getenv("MAPBOX_TOKEN"))

  })

  render_value=function(df){
    output$click <- renderDataTable({
      s <- event_data("plotly_click",source = "subset")
      print(s$y)
      return(DT::datatable(data_1[data_1$Country==s$y,])) 

    })
  }
 }
 shinyApp(ui,server)

【问题讨论】:

  • 如果您提供一个最小可重复的示例,您将最大限度地获得有用的答案。 This post 可能会有所帮助。在这里,您应该删除与您的特定问题不直接相关的所有内容,并提供您的输入数据。
  • 好的。我已经删除了与问题没有直接关系的所有内容。
  • 我的输入数据有 Country、Name、lat、lng 列。这是我绘制的数据。我希望在单击地图上的标记时显示另一个数据集。
  • 恕我直言,你没有。您还没有向我们提供file2.csv 的内容,(我认为)这是您的输入数据。任何格式化语句都不太可能是相关的。但我确实注意到您在renderPlot 中为fig 分配了一个情节,然后不返回任何内容。这可能与它有关。
  • 我的 file2.csv 包含公司名称、国家/地区、地址、邮编、城市、州、电话、传真等列。很抱歉,我没有理解您声明的第二部分。我需要返回什么? @Limey。能举个例子吗?

标签: r shiny


【解决方案1】:

我同意 Limey 的观点,即很难看穿你的例子,而且不可能重现它。此外,您的问题可能与this 问题重复。

但是,我经常偶然发现 - 可以说是可扩展的 - R plotly maps 的文档。因此我创建了一个完整的 MWE:

library(shiny)
library(plotly)
library(rjson)
library(DT)


ui <- fluidPage(

    # Application title
    titlePanel("Customdata for plotly maps"),

    # Sidebar 
    sidebarLayout(
        sidebarPanel(
            # see ?event_data for all choices
            radioButtons("event", "plotly's event", 
                         choiceNames = c("plotly_hover", "plotly_unhover", "plotly_click", "plotly_doubleclick",
                                         "plotly_selected", "plotly_selecting"), 
                         choiceValues = c("plotly_hover", "plotly_unhover", "plotly_click", "plotly_doubleclick",
                                          "plotly_selected", "plotly_selecting"))
        ),

        # Show map and table
        mainPanel(
           plotlyOutput("map"),
           DTOutput('tbl')
        )
    )
)

# Define server logic required 
server <- function(input, output, session) {

    
    output$map <- renderPlotly({

        # see https://plotly.com/r/choropleth-maps/

        url <- 'https://raw.githubusercontent.com/plotly/datasets/master/election.geojson'
        geojson <- rjson::fromJSON(file=url)
        url2<- "https://raw.githubusercontent.com/plotly/datasets/master/election.csv"
        df <- read.csv(url2)
        g <- list(
            fitbounds = "locations",
            visible = FALSE
        )
        fig <- plot_ly(source = "map") 
        fig <- fig %>% add_trace(
            type="choropleth",
            geojson=geojson,
            customdata = df$district_id, # specify whatever var from df you want
            locations= df$district,
            z=df$Bergeron,
            colorscale="Viridis",
            featureidkey="properties.district"
        )
        fig <- fig %>% layout(
            geo = g
        )
        fig <- fig %>% colorbar(title = "Bergeron Votes")
        fig <- fig %>% layout(
            title = "2013 Montreal Election"
        )
        fig %>% event_register(event = input$event)
        
            })
    
    output$tbl = renderDT(
        selected <- event_data(event = input$event, source = "map")    
        )

}

# Run the application 

shinyApp(ui = ui, server = server)

不需要您的 onRender(),只需指定 customdata(您没有?)并使用 event_register()event_data()

【讨论】:

  • 它给了我错误:“arg”应该是“plotly_hover”、“plotly_unhover”、“plotly_click”、“plotly_doubleclick”、“plotly_selected”、“plotly_selecting”、“plotly_brushed”、“ plotly_brushing”、“plotly_deselect”、“plotly_relayout”、“plotly_restyle”、“plotly_legendclick”、“plotly_legenddoubleclick”、“plotly_clickannotation”、“plotly_afterplot”、“plotly_sunburstclick”
  • 我添加了自定义数据并尝试实现您的代码,但它给了我错误
  • 奇怪。此错误是否发生在我的 MWE 中或当您调整我的 MWE 时?尝试用例如替换 input$event “plotly_click”
  • 我在调整 MWE 时将 input$event 替换为“plotly_click”。我得到一个包含曲线编号、点编号和自定义数据的表格。点击标记时如何显示国家对应的数据行?
  • 另外,我有下拉菜单,菜单中的每个选项都显示一个地图。当我在下拉菜单中从一个选项切换到另一个选项时,上一个 garph 的表格是否仍然存在?我怎么解决这个问题?谢谢@thmschk
【解决方案2】:

@thmsckh。我已经能够解决单击标记时加载表格的问题。但是我遇到了一个新问题。这是我为说明问题而创建的 MWE。当我从下拉菜单中选择并单击标记时,会出现该点的表格,但是当我切换到下拉菜单上的其他选项时,先前选项中的表格仍然存在。我该如何解决这个问题?

library(plotly)
library(dplyr)
library(shiny)
library(htmlwidgets)
library(DT)
library(ggplot2)
a<- datasets::mtcars
print(a)

ui <- fluidPage( 
  selectInput("var","Select a map type:",choices=list("Select","Map1","Map2")),
  plotlyOutput(outputId = "Plot"),
  DT::dataTableOutput('click'),
  DT::dataTableOutput('click1')

)

server <- function(input, output,session) {

  Plot1 <- reactive({
    render_value(a)
    fig <- plot_ly(
      type = 'scatter',
      x = mtcars$hp,
      y = mtcars$qsec,
      source="subset1",
      customdata=rownames(mtcars),
      text = paste("Make: ", rownames(mtcars),
                   "<br>hp: ", mtcars$hp,
                   "<br>qsec: ", mtcars$qsec,
                   "<br>Cyl: ", mtcars$cyl),
      hoverinfo = 'text',
      mode = 'markers',
      transforms = list(
        list(
          type = 'groupby',
          groups = mtcars$cyl,
          styles = list(
            list(target = 4, value = list(marker =list(color = 'blue'))),
            list(target = 6, value = list(marker =list(color = 'red'))),
            list(target = 8, value = list(marker =list(color = 'black')))
          )
        )
      )
    )

    fig
  })

  Plot2<- reactive({
    render_value1(a)
    fig <- plot_ly(mtcars, x = ~disp, color = I("black"), source = 
 "subset2",customdata=rownames(mtcars))
    fig <- fig %>% add_markers(y = ~mpg, text = rownames(mtcars), showlegend = 
FALSE)
    fig <- fig %>% add_lines(y = ~fitted(loess(mpg ~ disp)),
                             line = list(color = '#07A4B5'),
                             name = "Loess Smoother", showlegend = TRUE)
    fig <- fig %>% layout(xaxis = list(title = 'Displacement (cu.in.)'),
                          yaxis = list(title = 'Miles/(US) gallon'),
                          legend = list(x = 0.80, y = 0.90))

    fig

  })

  varinput<- reactive({
    switch(input$var,
           "Map1"=Plot1(),
           "Map2"=Plot2()
    )
  })

  output$Plot<- renderPlotly({
    varinput()
  })

  render_value=function(df_1){
    output$click <- renderDataTable({
      s <- event_data("plotly_click",source="subset1")
      print(s)
      return(DT::datatable(df_1[rownames(df_1) %in% 
 s$customdata,c('mpg','cyl',"hp","drat","wt","qsec")])) 
  
    })
  }
  render_value1=function(df_2){
    output$click1 <- renderDataTable({
      s <- event_data("plotly_click",source="subset2")
      print(s)
      return(DT::datatable(df_2[rownames(df_2) %in% 
s$customdata,c('mpg','cyl',"hp","drat","wt","qsec")])) 
  
    })
  }
}
shinyApp(ui,server)

【讨论】:

    猜你喜欢
    • 2021-05-19
    • 2018-05-04
    • 2017-08-05
    • 1970-01-01
    • 1970-01-01
    • 2017-11-03
    • 2016-07-28
    • 2017-04-10
    相关资源
    最近更新 更多