-1
library(shinyjs)
library(plotly)
library(shinydashboard)
library(shinycssloaders)
library(shiny)
library(dplyr)
library(DT)
library(tidyr)
library(shinycustomloader) 
library(tibble)
library(datapasta)

COL = c("#293a80","#39375b","#6915cf","#4b8e8d","#d55252","#293462","#940a37","#f54291","#f0134d","#b22222","#3c4245","#5d1451","#3c3d47")


ui<- fluidPage(
  fluidRow(column(width=12,
                  withLoader(plotlyOutput("plott1"),type = "html",loader = "loader4"))),
  fluidRow(column(width=12,
                  withLoader(plotlyOutput("plott2"),type = "html",loader = "loader1"))),
  fluidRow(column(width=12,
                  withLoader(plotlyOutput("plott3")))),
  fluidRow(column(width=12,
                  withLoader(plotlyOutput("plott4")))),
  fluidRow(column(width=12,
                  withLoader(plotlyOutput("plott5")))),
  fluidRow(verbatimTextOutput("plott6"))
  )

server<- function(input,output)

{
  output$plott1 <- renderPlotly({
    sp1<-tibble::tribble(
      ~DID, ~DistrictName, ~BlockName, ~CenterName, ~TotRaj, ~TotOtherState, ~StateCode,
      76,       "state",     "null",      "null", 7656454,        5645345,     "null"
    )


    ds <- data.frame(labels = c("Rajasthan","Other_State"),
                     values = c(sp1$TotRaj,sp1$TotOtherState)
    )

    plot_ly(ds, labels = ~labels, values = ~values,type = 'pie',source ='listenhere1',
            textposition = 'inside',
            textinfo = 'label+percent',
            insidetextfont = list(color = '#FFFFFF'),
            marker = list(colors = c('#5d1451','#745c97'),
                          line = list(color =colors , width = 1)),showlegend = FALSE) %>% 
      layout(
        xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
        yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))
  }) 

  output$plott2 <- renderPlotly({
    s <- event_data("plotly_click", source = "listenhere1")
    req(!is.null(s))

    if(s$pointNumber == 0){

      sp2<-tibble::tribble(
        ~DID, ~DistrictName, ~BlockName, ~CenterName, ~TotRaj, ~TotOtherState, ~StateCode,
        101,           "a",     "null",      "null",  564534,         564534,     "null",
        201,           "b",     "null",      "null",  675645,         765645,     "null",
        301,           "c",     "null",      "null",  765645,         786756,     "null",
        401,           "d",     "null",      "null",  987656,         764534,     "null",
        501,           "e",     "null",      "null",  675645,         543423,     "null",
        601,           "f",     "null",      "null",  765434,         231234,     "null",
        701,           "g",     "null",      "null",  564534,         763423,     "null",
        801,           "h",     "null",      "null",  234565,         567876,     "null",
        901,           "i",     "null",      "null",  985646,         876345,     "null",
        102,           "j",     "null",      "null",  876754,         453675,     "null",
        202,           "k",     "null",      "null",  876756,         876754,     "null"
      )

      layout <- list(
        font = list(size = 12),
        title = " District-Wise",
        xaxis = list(title = "district"),
        yaxis = list(title = "records",automargin = TRUE)
      )

      p <- plot_ly(sp2, x = sp2$DistrictName, y = sp2$TotRaj, type = 'bar', name = '',source = 'link3',key = ~paste(sp2$DID, sep = ""),marker = list(color = '#baabda')) %>%
        add_trace(y = sp2$TotOtherState, name = 'Other_State',marker = list(color = '#58508d')) %>%
        layout(yaxis = list(title = ''), barmode = 'stack')
    }
    else {
      sp2<-tibble::tribble(
        ~DID, ~DistrictName, ~BlockName, ~CenterName, ~TotRaj, ~TotOtherState, ~StateCode,
        101,           "a",     "null",      "null",  564534,         564534,     "null",
        201,           "b",     "null",      "null",  675645,         765645,     "null",
        301,           "c",     "null",      "null",  765645,         786756,     "null",
        401,           "d",     "null",      "null",  987656,         764534,     "null",
        501,           "e",     "null",      "null",  675645,         543423,     "null",
        601,           "f",     "null",      "null",  765434,         231234,     "null",
        701,           "g",     "null",      "null",  564534,         763423,     "null",
        801,           "h",     "null",      "null",  234565,         567876,     "null",
        901,           "i",     "null",      "null",  985646,         876345,     "null",
        102,           "j",     "null",      "null",  876754,         453675,     "null",
        202,           "k",     "null",      "null",  876756,         876754,     "null"
      )

      tablename=rowSums(cbind(sp2$TotRaj,sp2$TotOtherState),na.rm=TRUE)

      layout <- list(
        font = list(size = 12),
        title = " Other-State",
        xaxis = list(title = "RECORDS"),
        yaxis = list(title ="STATES" ,automargin = TRUE)
      )

      p <- plot_ly(sp2, colors = COL, marker = list(color = COL),source = 'linkhere',orientation='h',key = ~paste(sp2$DID, sep = "")) %>%
        add_trace( x =sp2$TotOtherState,y = sp2$StateName,name = "states",type = 'bar') %>%
        layout( font = layout$font, title = layout$title, xaxis = layout$xaxis, yaxis = layout$yaxis)
    }
  })

  output$plott3 <- renderPlotly({

    d<-event_data('plotly_click',source = 'link3')
    if(is.null(d)==F){
      sp3<-data.frame(stringsAsFactors=FALSE,
                      DID = c(101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101),
                      DistrictName = c("a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a"),
                      BlockName = c("aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg", "hhh",
                                    "iii", "jjj", "kkk"),
                      CenterName = c("null", "null", "null", "null", "null", "null", "null",
                                     "null", "null", "null", "null"),
                      TotRaj = c(564534, 675645, 765645, 987656, 675645, 765434, 564534,
                                 234565, 985646, 876754, 876756),
                      TotOtherState = c(564534, 765645, 786756, 764534, 543423, 231234, 763423,
                                        567876, 876345, 453675, 876754),
                      StateCode = c("null", "null", "null", "null", "null", "null", "null",
                                    "null", "null", "null", "null"),
                      CID = c("c01", "c02", "c03", "c04", "c05", "c06", "c07", "c08",
                              "c09", "c10", "c11")
      )

      p <- plot_ly(sp3, x = sp3$BlockName, y = sp3$TotRaj, type = 'bar', name = '',key = ~paste(sp3$DID,sep = ",",sp3$CID), source = 'link1',marker = list(color = '#537ec5')) %>%
        add_trace(y = sp3$TotOtherState, name = 'other-state',marker = list(color = '#57007e')) %>%
        layout(yaxis = list(title = 'sonography block_level'),xaxis = list(title = 'Block name'), barmode = 'group',title='')}
    else{
      return(NULL)
    }

  })

  output$plott4 <- renderPlotly({
    d<-event_data('plotly_click',source = 'link1')
    if(is.null(d)==F){
      sp4<-data.frame(stringsAsFactors=FALSE,
                      DID = c(101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101),
                      DistrictName = c("a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a"),
                      BlockName = c("aaa", "aaa", "aaa", "aaa", "aaa", "aaa", "aaa", "aaa",
                                    "aaa", "aaa", "aaa"),
                      CenterName = c("abc", "bac", "dac", "efc", "ghc", "hic", "jkl", "mnl",
                                     "lkj", "ghj", "kjh"),
                      TotRaj = c(2345, 2343, 6754, 7656, 8767, 6756, 4534, 5678, 6756,
                                 5434, 9876),
                      TotOtherState = c(4532, 2345, 3456, 4567, 9845, 9876, 6756, 5645, 4534,
                                        5645, 7865),
                      StateCode = c("null", "null", "null", "null", "null", "null", "null",
                                    "null", "null", "null", "null"),
                      CID = c("c01", "c02", "c03", "c04", "c05", "c06", "c07", "c08",
                              "c09", "c10", "c11")
      )


      p <- plot_ly(sp4, x = sp4$TotRaj, y =sp4$CenterName , type = 'bar', name = 'rajasthan',key = ~paste(sp4$CID, sep = ""),source = "hey",
                   marker = list(color = '#1a3e59',
                                 line = list(color = 'rgba(246, 78, 139, 1.0)'))) %>%
        add_trace(x = sp4$TotFormFOtherState, name = 'other-state',
                  marker = list(color = '#baabda',
                                line = list(color = 'rgba(58, 71, 80, 1.0)'))) %>%
        layout(barmode = 'stack',
               xaxis = list(title = "Centre Data"),
               yaxis = list(title ="Centre Name"))}
    else{return(NULL)}
  })

  output$plott5 <- renderPlotly({
    s <- event_data("plotly_click", source = "linkhere")
    req(!is.null(s))

      sp5<-tibble::tribble(
               ~DID, ~DistrictName, ~BlockName, ~CenterName, ~TotRaj, ~TotOtherState, ~StateCode,   ~CID, ~StateName,
             "null",        "null",     "null",       "nul",   "nul",           4532,          1, "null",    "alpha",
             "null",        "null",     "null",       "nul",   "nul",           2345,          2, "null",     "beta",
             "null",        "null",     "null",       "nul",   "nul",           3456,          3, "null",     "gama",
             "null",        "null",     "null",       "nul",   "nul",           4567,          4, "null",    "theta",
             "null",        "null",     "null",       "nul",   "nul",           9845,          5, "null",      "abn",
             "null",        "null",     "null",       "nul",   "nul",           9876,          6, "null",      "mnb",
             "null",        "null",     "null",       "nul",   "nul",           6756,          7, "null",      "vbg",
             "null",        "null",     "null",       "nul",   "nul",           5645,          8, "null",      "hjg",
             "null",        "null",     "null",       "nul",   "nul",           4534,          9, "null",      "klj",
             "null",        "null",     "null",       "nul",   "nul",           5645,         10, "null",      "ghj",
             "null",        "null",     "null",       "nul",   "nul",           7865,         11, "null",      "jhg"
             )


      layout <- list(
        font = list(size = 12),
        title = " District-Wise",
        xaxis = list(title = "district"),
        yaxis = list(title = "records",automargin = TRUE)
      )

      p <- plot_ly(sp5, x = sp5$StateName, y = sp5$TotOtherState, type = 'bar', name = '',source = 'link3',key = ~paste(sp5$DID, sep = ""),marker = list(color = COL))

  })


  output$plott6<-renderPrint({
    s<-event_data("plotly_click",source = "link1")
    if(length(s)==0)
    {
      "CLICK ON BARCHART TO PRINT THE VALUES!"
    }
    else{
      as.list(s)
    }
  })

}



runApp(list(ui = ui, server = server), launch.browser = TRUE)

screenshots to make it understand better... enter image description here enter image description here

i am using the stored procedure from ms SQL server for this purpose but created it the simplest way possible to make it run on other's machines. as shown in the images, how to break the key value into two values and store them in two different variables.how to split and store them.

1
  • You are asking this question for the second time now. To split your key you can use something like unlist(strsplit("101,c07", split=",")). However I'd recommend using a unique key and filtering your source data according to the selection instead of passing your custom data via the key. Nov 19, 2019 at 12:57

1 Answer 1

0

Here is a minimal example on how to filter your dataset based on plotly_click-events and pass the resulting variables as parameters to a SQL query:

library(shiny)
library(plotly)
library(datasets)

ui <- fluidPage(
  plotlyOutput("myPlot"),
  tableOutput("myQueryResult"),
  textOutput("myExampleQuery")
)

keyedIris <- iris

# create unique row id
keyedIris$myKey <- 1:nrow(keyedIris)

server <- function(input, output, session) {
  output$myPlot <- renderPlotly(plot_ly(keyedIris, x = ~Sepal.Length, y = ~Sepal.Width, color = ~Species, type = "scatter", mode = "markers", source = "mySource", key = ~myKey))

  filteredIris <- reactive({
    myPlotEvents <- event_data(event = "plotly_click", source = "mySource")
    keyedIris[keyedIris$myKey %in% myPlotEvents$key,]
  })

  output$myQueryResult <- renderTable({
    filteredIris()
    })

  output$myExampleQuery <- renderText({
    sprintf("SELECT * FROM iris WHERE Species IN (%s) AND Petal.Length IN (%s) AND Petal.Width IN (%s)", filteredIris()$Species, filteredIris()$Petal.Length, filteredIris()$Petal.Width)
  })

}

shinyApp(ui, server)

Result

8
  • thanks for your help, i have been looking for this answer for a very long time but in your case, it is passing single key on each plotly_click event, but in my case,wanna pass more than one (might be twice or thrice) on single click event, i mean for single case, i want to pass multiple values, let's say, in SP it will kinda look like this...d<-event_data('plotly_click',source = 'linkhere') if(is.null(d)==F){qrydd=paste("exec db_name..[sp_name]",d$key,",'','','','','0','2','15','','01/01/2017','31/12/2017'") and linkhere key would be like this key = ~paste(sp3$DID,sep = ",",sp3$CID) Nov 20, 2019 at 4:46
  • i hope, you would understand what i am trying to explain here Nov 20, 2019 at 4:47
  • I understood you very well. With the above I wanted to show that you don't need to pass multiple keys. You can always break the problem down to a single key and filter a data.frame to provide you with multiple variables for later use. As you can see, in my above example using a single key leads to a query with three parameters. Nov 20, 2019 at 5:37
  • okay, i got it, earlier i was looking it from my own perspective that's where i went wrong, first, i need to filter the data, then apply the key concepts to them, i beg your pardon for not understanding the problem very well earlier, thanks for your help though,no one was paying attention to this problem until you came to rescue,thanks again,your helps means a lot to newbie like us to this filed Nov 20, 2019 at 6:08
  • 1
    thanks a lot for bearing with me this long on this issue,it worked for me and achieved what i was looking for even beyond my imagination, thanks again for your concern and help throughout this issue Nov 21, 2019 at 7:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.