title: Linked Click for maps in Plotly R
body: <p>Data :</p>
  
  <p><a href="https://www.kaggle.com/wood2174/mapkickstarter" rel="nofollow noreferrer">https://www.kaggle.com/wood2174/mapkickstarter</a></p>
  
  <p>So i have a map im making with shiny and plotly and id like to click on a state and then pull up that state to get info on the counties in that state. Well iv seen other linked plot examples in plotly but I am not sure how to set up my map in this way. this is my plot before clicking. <a href="https://i.stack.imgur.com/vocUJ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vocUJ.jpg" alt="enter image description here"></a></p>
  
  <p>This is my map after iv clicked a state:
  <a href="https://i.stack.imgur.com/lr9YH.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lr9YH.jpg" alt="enter image description here"></a></p>
  
  <p>I am pretty sure I am not passing arguments the correct way between the two using the event_data argument. 
  The argument i am passing is going to be the name of the state and that name will be pout into my function called CT as a character as to call up the state name so i can find the county data from clicked on state, the other, data and pop are two other data frames being passed into the function. 
  This is what the function douse outside of shiny server and it produces and interactive hover map:
  <a href="https://i.stack.imgur.com/KOGjX.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KOGjX.jpg" alt="enter image description here"></a>  </p>
  
  <p>Code:</p>
  
  <pre><code>ui &lt;- fluidPage(mainPanel(
    navbarPage(
      "Kickstarter",
      navbarMenu(
        "Maps",
        tabPanel("US Map", plotlyOutput(
          "plotMap", height = 900, width = 1200
        )),
        tabPanel("County Map",
                 plotlyOutput("Smap"),
                 plotlyOutput("Cmap"))
      ),
      tabPanel(
        "Interaction",
        plotlyOutput("plotInt", height = 900, width = 1200)
      ),
      navbarMenu(
        "Barplots",
        tabPanel("Citys", plotlyOutput(
          "plotBar1", height = 900, width = 1200
        )),
        tabPanel(
          "Catigories",
          plotlyOutput("plotBar2", height = 900, width = 1200)
        )
      )
    )
  ))
  
  
       server &lt;- function(input, output, session) {
    #add reactive data information. Dataset = built in diamonds data
    H &lt;- read_csv("C:/Users/clint/Documents/R/Personal work/Masters Project/MasterKickstarter.csv")
    M &lt;- read_csv("C:/Users/clint/Documents/R/Personal work/Masters Project/data sets/Mapping.csv")
    C &lt;- read_csv("C:/Users/clint/Documents/R/Personal work/Masters Project/data sets/County.csv")
  
    H &lt;- as.data.frame(H)
    M &lt;- as.data.frame(M)
    C &lt;- as.data.frame(C)
  
    ### Plotting top twenty citys for a kick ###
    # calculate frequencies
    tab &lt;- table(H$City)
    # sort
    tab_s &lt;- sort(tab)
    # extract 10 most frequent nationalities
    top10 &lt;- tail(names(tab_s), 25)
    # subset of data frame
    d_s &lt;- subset(H, City %in% top10)
    # order factor levels
    d_s$City &lt;- factor(d_s$City, levels = rev(top10))
  
    #function for capitalization
    simpleCap &lt;- function(x) {
      s &lt;- strsplit(x, " ")[[1]]
      paste(toupper(substring(s, 1, 1)),
            substring(s, 2),
            sep = "",
            collapse = " ")
    }
  
  
  
    M$code &lt;- state.abb[match(M$State, state.name)]
  
    #making temp sets that fit for interactive maps
    H = H[!duplicated(H[, "City"], fromLast = T), ]
    H$State &lt;- sapply(as.character(H$State), simpleCap)
    H$code &lt;- state.abb[match(H$State, state.name)]
  
    H$City &lt;- factor(H$City)
  
    #making quartiles for plotting size
    H$q &lt;-
      with(H, cut(All_Time_Backers_city, quantile(All_Time_Backers_city)))
    levels(H$q) &lt;-
      paste(c("1st", "2nd", "3rd", "4th", "5th"), "Quantile")
    H$q &lt;- as.ordered(H$q)
  
  
    CT &lt;- function(r,data,pop){
  
      cali &lt;- map_data("county") %&gt;%
        filter(region == r)
  
      cali_pop &lt;- left_join(cali, pop, by = c("subregion","region"))
  
      cali_pop$pop_cat &lt;- with(cali_pop,
                               (paste0(cali_pop$subregion, "&lt;br /&gt;",
                                       round(cali_pop$MedianBackers), "Median Backers ||",round(cali_pop$MedianUSD),"MedianUSD","&lt;br /&gt;",
                                       round(cali_pop$MeanBackers), "Mean Backers ||",round(cali_pop$MeanUSD),"MeanUSD","&lt;br /&gt;",
                                       (cali_pop$TotalBackers), "Total Backers ||",(cali_pop$TotalUSD), "TotalUSD")))
      cali_pop[is.na(cali_pop)] &lt;- 0
      cali_pop$pop_cat &lt;- as.factor(cali_pop$pop_cat)
  
      p &lt;- cali_pop %&gt;%
        group_by(group) %&gt;%
        plot_ly(x = ~long, y = ~lat, color = ~pop_cat, colors = c('#ffeda0','#f03b20')) %&gt;%
        add_polygons(line = list(width = 0.4),showlegend = FALSE) %&gt;%
        add_polygons(
          fillcolor = 'transparent',
          line = list(color = 'black', width = 0.5),
          showlegend = FALSE
        ) %&gt;%
        layout(
          title = "Backers by County",
          titlefont = list(size = 10),
          xaxis = list(title = "", showgrid = FALSE,
                       zeroline = FALSE, showticklabels = FALSE),
          yaxis = list(title = "", showgrid = FALSE,
                       zeroline = FALSE, showticklabels = FALSE)
        )
      p
  
    }  
  
    output$Smap &lt;- renderPlotly({
      M$hover &lt;- with(M, paste(State))
      # give state boundaries a white border
      l &lt;- list(color = toRGB("white"), width = 2)
      # specify some map projection/options
      g &lt;- list(
        scope = 'north america',
        showland = TRUE,
        landcolor = toRGB("grey83"),
        subunitcolor = toRGB("white"),
        countrycolor = toRGB("white"),
        showlakes = TRUE,
        lakecolor = toRGB("white"),
        showsubunits = TRUE,
        showcountries = TRUE,
        resolution = 50,
        projection = list(type = 'conic conformal',
                          rotation = list(lon = -100)),
        lonaxis = list(
          showgrid = TRUE,
          gridwidth = 0.5,
          range = c(-140,-55),
          dtick = 5
        ),
        lataxis = list(
          showgrid = TRUE,
          gridwidth = 0.5,
          range = c(15, 70),
          dtick = 5
        )
      )
  
      # Plotting a US interactive map
      p &lt;- plot_geo(source = "CCM") %&gt;%
        add_trace(M,
          z = ~ M$`Mean Bakers`,
          text = ~ M$hover,
          x = ~M$State,
          locations = ~ M$code,
          locationmode = "USA-states"
        ) %&gt;%
        colorbar(title = "Money") %&gt;%
        layout(
          title = 'Kickstarter USA',
          geo = g
        )
      p
    })
  
    output$Cmap &lt;- renderPlotly({
      s &lt;- event_data("plotly_click", source = "CCM")
  
      if (length(s)){
  
        var &lt;- s[["x"]]
        d &lt;- setNames(M[var], "x")
        CT(d,H,C)
      }
    })
  
    output$plotBar1 &lt;- renderPlotly({
      p1 &lt;- d_s %&gt;% count(City, status) %&gt;%
        plot_ly(x = ~ City,
                y = ~ n,
                color = ~ status)
      p1
  
    })
  
    output$plotBar2 &lt;- renderPlotly({
        p2 &lt;- H %&gt;% count(Categories, status) %&gt;%
          plot_ly(x = ~ Categories,
                  y = ~ n,
                  color = ~ status)
  
        p2
      })
  
    output$plotMap &lt;- renderPlotly({
      #preparing the hover text
      M$hover &lt;- with(
        M,
        paste(
          State,
          '&lt;br&gt;',
          "Pledges_total",
          M$`Total Pledged`,
          "Backers_total",
          M$`Total Backers`,
          "&lt;br&gt;",
          "Mean_pledges",
          M$`Mean Campaign USD`,
          "Mean_backers",
          M$`Mean Bakers`,
          "&lt;br&gt;",
          "Median Goal %",
          M$`Median Percent of Goal`,
          "Number of projects",
          M$`Projects Per`
        )
      )
  
      g &lt;- list(
        scope = 'north america',
        showland = TRUE,
        landcolor = toRGB("grey83"),
        subunitcolor = toRGB("white"),
        countrycolor = toRGB("white"),
        showlakes = TRUE,
        lakecolor = toRGB("white"),
        showsubunits = TRUE,
        showcountries = TRUE,
        resolution = 50,
        projection = list(type = 'conic conformal',
                          rotation = list(lon = -100)),
        lonaxis = list(
          showgrid = TRUE,
          gridwidth = 0.5,
          range = c(-140,-55),
          dtick = 5
        ),
        lataxis = list(
          showgrid = TRUE,
          gridwidth = 0.5,
          range = c(15, 70),
          dtick = 5
        )
      )
  
      #plotting an interactive map for states and cities
      p &lt;- plot_geo(H, sizes = c(5, 250)) %&gt;%
        add_markers(
          x = ~ H$Longitude,
          y = ~ H$Latitude,
          size = ~ H$All_Time_Backers_city,
          color = ~ q,
          text = ~ paste(H$City, "&lt;br /&gt;",
                         H$All_Time_Backers_city, "Backers")
        ) %&gt;%
        add_trace(M,
                  z = ~ M$`Mean Campaign USD`,
                  text = ~ M$hover,
                  locations = ~ M$code
                  ,
                  locationmode = "USA-states"
        ) %&gt;%
        layout(title = 'Backers City All Time', geo = g)
      p
  
    })
  
    output$plotInt &lt;- renderPlotly({
      p &lt;- H %&gt;%
        plot_ly() %&gt;%
        add_trace(
          type = 'parcoords',
          line = list(
            color = ~ backers_count,
            colorscale = 'Jet',
            showscale = TRUE,
            reversescale = TRUE,
            cmin = 2,
            cmax = 1500
          ),
          dimensions = list(
            list(
              range = c(0, 92),
              constrantrange = c(0, 30),
              label = 'Time',
              values = ~ Length_of_kick
            ),
            list(
              range = c(0, 2000),
              constraintrange = c(0, 1000),
              label = 'Pledge USD',
              values = ~ Pledge_per_person
            ),
            list(
              range = c(0, 8000000),
              constrantrange = c(0, 3000000),
              label = 'Population',
              values = ~ MasterKickstarter$City_Pop
            ),
            list(
              range = c(0, 1600),
              constraintrange = c(0, 500),
              label = 'Days Making',
              values = ~ Days_spent_making_campign
            ),
            list(
              tickvals = c(1, 2, 3, 4, 5),
              ticktext = c('cancled', 'failed', 'live', 'successful', 'suspended'),
              label = 'Status',
              values = ~ as.integer(as.factor(status))
            ),
            list(
              range = c(0, 1000000),
              constraintrange = c(0, 300000),
              label = 'Goal',
              values = ~ goal
            ),
            list(
              tickvals = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15),
              ticktext = c(
                'art',
                'comics',
                'crafts',
                'dance',
                'design',
                'fasion',
                'film',
                'food',
                'games',
                'journalism',
                'music',
                'photogaphy',
                'publishing',
                'technology',
                'theator'
              ),
              label = 'Catigories',
              values = ~ as.integer(as.factor(Categories))
            ),
            list(
              range = c( ~ min(Prct_goal), 1200),
              constraintrange = c(0, 500),
              label = 'Prct goal',
              values = ~ Prct_goal
            )
          )
        )
      p
    })
  
  }
  
  shinyApp(ui, server)
  </code></pre>