I'm trying to print an interactive pie chart. On a click on the plot another trace should be added. I'm using event_data for this. When the trace is added, on the next click anywhere on the page the trace shall be removed. I didn't find a solution for that. I don't know how to overwrite the onclick-event after another click.
The next Problem would be to remove the before added trace. I think i could use plotlyProxy for that like in Removing traces by name using plotlyProxy (or accessing output schema in reactive context)
Afterwards you can see my code
library(shiny)
library(data.table)
library(plotly)
ui <- basicPage(
mainPanel(
fluidRow(column(8, plotly::plotlyOutput("myplot", height = "800px")))
)
)
server <- function(input, output, session) {
testdata = data.frame("Orga" = c("Li", "La", "Le", "Lu", "De", "Va", "Xul", "Jin"),
"Dachorga" = c("Bla", "Bla", "Blu", "Blu", "Blub", "Blub", "Lol", "Lol"),
"Umsatz.Orga" = c(20000, 10000, 12000, 3000, 100, 2400, 205000, 95000))
testdata = data.table(testdata)
testdata_agg = testdata[, sum(Umsatz.Orga), by=Dachorga]
output$myplot <- renderPlotly({
p <- testdata_agg %>%
group_by(Dachorga) %>%
plot_ly(labels = ~Dachorga, values = ~V1, hoverinfo = 'label+percent+value') %>%
add_pie(hole = 0.6) %>%
layout(title = "Donut charts using Plotly", showlegend = F,
xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))
d <- event_data("plotly_click")
if (!is.null(d)) {
p = add_pie(p, data = testdata[Dachorga == "Bla"], labels = ~Orga, values = ~Umsatz.Orga, hole = 0.5,
hoverinfo = 'label+percent+value', domain = list(
x = c(0.1, 0.9),
y = c(0.1, 0.9)),
marker = list(hover = list(color = "white")))
}
p
})
}
shinyApp(ui = ui, server = server)
Sorry for my bad english and thanks in advance
One can use a small javascript code to detect one click on the document, and send the result to the shiny server with Shiny.setInputValue. Then one can control the plot with the help of a reactive value.
library(shiny)
library(data.table)
library(plotly)
js <- "
$(document).ready(function(){
$(document).on('click', function(){
Shiny.setInputValue('click_on_doc', true, {priority: 'event'});
})
})"
ui <- basicPage(
tags$head(tags$script(HTML(js))),
mainPanel(
fluidRow(column(8, plotly::plotlyOutput("myplot", height = "800px")))
)
)
server <- function(input, output, session) {
testdata <- data.frame("Orga" = c("Li", "La", "Le", "Lu", "De", "Va", "Xul", "Jin"),
"Dachorga" = c("Bla", "Bla", "Blu", "Blu", "Blub", "Blub", "Lol", "Lol"),
"Umsatz.Orga" = c(20000, 10000, 12000, 3000, 100, 2400, 205000, 95000))
testdata <- data.table(testdata)
testdata_agg <- testdata[, sum(Umsatz.Orga), by=Dachorga]
plot <- testdata_agg %>%
group_by(Dachorga) %>%
plot_ly(labels = ~Dachorga, values = ~V1, hoverinfo = 'label+percent+value') %>%
add_pie(hole = 0.6) %>%
layout(title = "Donut charts using Plotly", showlegend = F,
xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))
click <- reactiveVal(FALSE)
observe({
event <- !is.null(event_data("plotly_click"))
click(event)
})
observeEvent(input$click_on_doc, {
click(FALSE)
})
output$myplot <- renderPlotly({
if (click()) {
p <- add_pie(plot, data = testdata[Dachorga == "Bla"], labels = ~Orga,
values = ~Umsatz.Orga, hole = 0.5,
hoverinfo = 'label+percent+value', domain = list(
x = c(0.1, 0.9),
y = c(0.1, 0.9)),
marker = list(hover = list(color = "white")))
}else{
p <- plot
}
p
})
}
shinyApp(ui = ui, server = server)
I have not understood your "next problem". Perhaps open a new question and try to clarify.
Related
could someone tell me why leaflet doesn't read the data.frame properly created inside the server function of shiny?
It doesn't show any map when executed, as soon as I try to addCirkleMarkers by the data I gathered before?
It works perfectly, when I do it outside of shiny without input$type and just "Coworking" as search_string and keyword.
library(shiny)
library(shinydashboard)
library(leaflet)
library(rgdal)
library(dplyr)
library(data.table)
library(leaflet.extras)
library(googleway)
library(tidyverse)
dashboard <- dashboardPage(
skin = "blue",
dashboardHeader(title = "Cluster-Dashboard"),
dashboardSidebar(
textInput("type", "Nutzung")),
dashboardBody(
fluidRow(box(width = 12, leaflet::leafletOutput(outputId = "mymap"))),
fluidRow(box(width = 12, dataTableOutput(outputId = "Coworking")))
))
db_server <- function(input, output) {
# gathering data and cleaning it
output$Coworking <- renderDataTable({
Coworking_2 <- google_places(
search_string = input$type,
location = c(52.52639577069,13.342801700749),
radius = 0.5,
keyword = input$type,
simplify = TRUE,
key = "Hidden")
keeps <- c("name", "formatted_address", "geometry", "place_id")
CoWorking_Clean = Coworking_2$results[keeps]
CoWorking_Clean_2 <- CoWorking_Clean %>%
unnest(geometry) %>%
unnest(location) %>%
subset(select = c("name", "formatted_address", "lat", "lng", "place_id")) %>%
rename(address = "formatted_address")
})
output$mymap <- reactive({leaflet::renderLeaflet({Karte})})
Karte <- reactive({
leaflet (output$Coworking) %>%
addTiles() %>%
addProviderTiles(providers$CartoDB.PositronNoLabels) %>%
setView(13.412, 52.505, zoom = 11) %>%
addCircleMarkers(popup = ~as.character(name), label = ~as.character(name),fill =TRUE, fillColor ="#225287", stroke =FALSE, opacity = 0.5, group = "Companies",
labelOptions = labelOptions(noHide = T, textOnly = TRUE, direction = "bottom", style = list("color" = "black", "font-size" = "11px", "font-family" = "AkkuratStd", "font-style" = "Thin")))
}
)}
shinyApp (ui = dashboard , server = db_server)
the dataTableOutput "Coworking" clarifies that the dataTable was created and the information should be able to read by leaflet. there are long and lat inside. Im freaking out....
there is no error, the shiny app loads instant and everything works perfect except the leaflet map. There is even no error...
I spoted some errors in your server function, but i wasn't able to test if the code below solves the problem because of the api token.
db_server <- function(input, output) {
cowork <- reactive({
Coworking_2 <- google_places(
search_string = input$type,
location = c(52.52639577069,13.342801700749),
radius = 0.5,
keyword = input$type,
simplify = TRUE,
key = "Hidden")
keeps <- c("name", "formatted_address", "geometry", "place_id")
CoWorking_Clean = Coworking_2$results[keeps]
CoWorking_Clean_2 <- CoWorking_Clean %>%
unnest(geometry) %>%
unnest(location) %>%
subset(select = c("name", "formatted_address", "lat", "lng", "place_id")) %>%
rename(address = "formatted_address")
return(CoWorking_Clean_2)
})
output$Coworking <- renderDataTable({
cowork()
})
output$mymap <- renderLeaflet({
leaflet (cowork()) %>%
addTiles() %>%
addProviderTiles(providers$CartoDB.PositronNoLabels) %>%
setView(13.412, 52.505, zoom = 11) %>%
addCircleMarkers(popup = ~as.character(name), label = ~as.character(name),fill =TRUE, fillColor ="#225287", stroke =FALSE, opacity = 0.5, group = "Companies",
labelOptions = labelOptions(noHide = T, textOnly = TRUE, direction = "bottom", style = list("color" = "black", "font-size" = "11px", "font-family" = "AkkuratStd", "font-style" = "Thin")))
})
}
I have the shiny app below which displays a bar chart with Country in yaxis and Value in xaxis. Im trying to change it to: Country as xaxis and Value as yaxis by clicking on Exchange actionButton(). I should toggle between those two bu clicking on Exchange
library(shiny)
library(DT)
Country<-c("EU","CHE","ITA")
Value<-c(3,2,1)
dat<-data.frame(Country,Value)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
actionButton("exc",
"Exchange")
),
mainPanel(
uiOutput(outputId = "plot")
)
)
)
server <- function(input, output) {
excplot <- reactiveVal(TRUE)
observeEvent(input$exc, {
excPlot(!excplot())
})
output[["bar1"]]<-renderPlotly({
fig1 <- plot_ly(dat, x = ~Value, y = ~Country,
type = 'bar', orientation = 'h',
hovertemplate = paste('%{y}', '<br>Value: %{x}<br>'),
marker = list(color = 'green')
)
fig1 <- fig1 %>% layout(
yaxis = list(title="",showgrid = FALSE, showline = FALSE, showticklabels = TRUE, domain= c(0, 0.85)),
xaxis = list(title="",zeroline = FALSE, showline = FALSE, showticklabels = FALSE, showgrid = FALSE))
fig1 <- fig1 %>% add_annotations(xref = 'x1', yref = 'y',
x = dat$Value* 1.1 + 0.5, y = dat$Country,
text = paste(round(dat$Value, 2), '%'),
font = list(family = 'Arial', size = 12, color = 'black'),
showarrow = FALSE)
fig1
})
output$plot <- renderUI({
plotlyOutput("bar1")
})
}
shinyApp(ui = ui, server = server)
Perhaps this will meet your needs.
library(shiny)
library(DT)
Country<-c("EU","CHE","ITA")
Value<-c(3,2,1)
dat<-data.frame(Country,Value)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
actionButton("exc", "Exchange")
),
mainPanel(
uiOutput(outputId = "plot")
)
)
)
server <- function(input, output) {
excplot <- reactiveVal(TRUE)
observeEvent(input$exc, {
excplot(!excplot())
})
output[["bar1"]]<-renderPlotly({
if (excplot()) {
dat$xvar <- dat$Value
dat$yvar <- dat$Country
hv <- "h"
myyaxis = list(title="",showgrid = FALSE, showline = FALSE, showticklabels = TRUE, domain= c(0, 0.85) )
myxaxis = list(title="",zeroline = FALSE, showline = FALSE, showticklabels = FALSE, showgrid = FALSE)
xx <- dat$xvar*1.1 + 0.1
yy <- dat$yvar
}else {
dat$yvar <- dat$Value
dat$xvar <- dat$Country
hv <- "v"
myxaxis = list(title="",showgrid = FALSE, showline = FALSE, showticklabels = TRUE, domain= c(0, 0.85) )
myyaxis = list(title="",zeroline = FALSE, showline = FALSE, showticklabels = FALSE, showgrid = FALSE)
xx <- dat$xvar
yy <- dat$yvar*1.1 + 0.1
}
fig1 <- plot_ly(dat, x = ~xvar, y = ~yvar,
type = 'bar', orientation = hv,
hovertemplate = paste('%{y}', '<br>Value: %{x}<br>'),
marker = list(color = 'green')
)
fig1 <- fig1 %>% layout(yaxis = myyaxis, xaxis = myxaxis )
fig1 <- fig1 %>% add_annotations(xref = 'x1', yref = 'y',
x = xx , y = yy,
text = paste(round(dat$Value, 2), '%'),
font = list(family = 'Arial', size = 12, color = 'black'),
showarrow = FALSE)
fig1
})
output$plot <- renderUI({
plotlyOutput("bar1")
})
}
shinyApp(ui = ui, server = server)
I'm trying to code a shiny app for plotting xy data. Each xy point is associated with several factors:
set.seed(1)
data.df <- data.frame(x = rnorm(1000), y = rnorm(1000),
sex = sample(c("F", "M"), 1000, replace = T),
age = sample(c("Y", "O"), 1000, replace = T),
group = sample(c("A", "B", "C", "D"), 1000, replace = T),
stringsAsFactors = F)
design.df <- data.frame(factor.name = c(c(rep("sex",2), rep("age",2), rep("group",4))),
factor.levels = c("F", "M","Y", "O","A", "B", "C", "D"), stringsAsFactors = F)
I would like to enable the user to subset the xy data (data.df) based on a selection of multiple rows from design.df using DT::renderDT within renderUI in the server, where the default selection is all rows of design.df. This works fine using this code:
suppressPackageStartupMessages(library(dplyr))
suppressPackageStartupMessages(library(shiny))
suppressPackageStartupMessages(library(DT))
server <- function(input, output)
{
output$design.idx <- renderUI({
output$design.df <- DT::renderDT(design.df, server = TRUE, selection = list(mode = "multiple", selected = rownames(design.df)[1:nrow(design.df)]))
DT::dataTableOutput("design.df")
})
xy.plot <- reactive({
if(!is.null(input$design.df_rows_selected)){
selected.design.df <- design.df[input$design.df_rows_selected,,drop = FALSE]
selected.idx <- lapply(unique(selected.design.df$factor.name), function(f) which(data.df[,f] %in% dplyr::filter(selected.design.df, factor.name == f)$factor.levels)) %>%
unlist() %>% unique()
plot.df <- data.df[selected.idx,,drop=F]
xy.plot <- suppressWarnings(plotly::plot_ly(marker = list(size = 3), type = 'scatter', mode = "markers", x = plot.df$x, y = plot.df$y, showlegend = FALSE) %>%
plotly::layout(xaxis = list(zeroline = FALSE, showticklabels = FALSE, showgrid = FALSE), yaxis = list(zeroline = FALSE, showticklabels = FALSE, showgrid = FALSE)))
} else{
xy.plot <- NULL
}
return(xy.plot)
})
output$outPlot <- plotly::renderPlotly({
xy.plot()
})
}
ui <- fluidPage(
titlePanel("Results Explorer"),
sidebarLayout(
sidebarPanel(
uiOutput("design.idx")
),
mainPanel(
plotly::plotlyOutput("outPlot")
)
)
)
shinyApp(ui = ui, server = server)
But I would also like to have a title or caption for the rendered datatable, so I tried replacing:
output$design.df <- DT::renderDT(design.df, server = TRUE, selection = list(mode = "multiple", selected = rownames(design.df)[1:nrow(design.df)]))
with:
output$design.df <- DT::renderDT(datatable(design.df, caption = "Subset Selection"), server = TRUE, selection = list(mode = "multiple", selected = rownames(design.df)[1:nrow(design.df)]))
in which case the selected = rownames(design.df)[1:nrow(design.df)] argument seems to be ignored and the default selection is no rows.
Changing selected = rownames(design.df)[1:nrow(design.df)] to selected = 1:nrow(design.df) makes no difference.
Any idea how to get both a title or caption to the rendered table together with have all rows as a pre-selection default?
You have to put selection in the datatable object:
output$design.df <- DT::renderDT(
datatable(design.df,
caption = "Subset Selection",
selection = list(mode = "multiple",
selected = rownames(design.df)[1:nrow(design.df)])
),
server = TRUE)
I have the following R codes within the shiny framework. Everything looks good, but the legend (Plese see this screenshot).
I want the legend to be updated on the basis of the users' selection of age group (60+, 65+, 85+), sex, or year. But it is not the case. That is, the legend's values remain unchanged, no matter what is selected from the left menu (Please see this screenshot). This makes the map useless if the 85+ is selected. Following is my entire codes.
I appreciate your help.
Nader
load("/Users/nadermehri/Desktop/map codes/nhmap.RData")
library(shiny)
library(leaflet)
ui <- fluidPage(
tabPanel(
"Interactive Maps",
tags$h5 (
)),
br(),
sidebarLayout(
sidebarPanel(
selectInput(
inputId = "Age_Group_map",
label = "Select the Age Group:",
selected = "60+",
selectize = F,
multiple = F,
choices = sort(unique(nhmap$Age_Group))
),
radioButtons(
inputId = "sex_map",
label = strong("Select Sex:"),
selected = "Both Sexes",
choices = sort(unique(nhmap$Sex))
),
sliderInput(
inputId = "Year_map",
label = "Year",
min = 2010,
max = 2050,
value = 2010,
step = 10,
sep = "",
pre = "",
animate = animationOptions(
interval = 1000,
loop = F,
playButton = tags$button("Play", style =
"background-color: #B61E2E ; color:white; margin-top: 10px; border:solid"),
pauseButton = tags$button("Pause", style =
"background-color: #B61E2E !important; color:white; margin-top: 10px; border:solid")
),
round = T,
width = "150%",
ticks = T
)),
mainPanel("Interactive", leafletOutput("int_map", height=500))))
server <- function(input, output) {
mapdata_ <- reactive ({
nhmap$Per <- round(nhmap$Per, 1)
out_map <- nhmap %>%
filter (
Age_Group %in% input$Age_Group_map,
Sex %in% input$sex_map,
Year %in% input$Year_map)
return(out_map)
})
output$int_map <- renderLeaflet ({
leaflet (mapdata_(),
pal8 <- c("#FFFFE5", "#D9F0A3", "#78C679", "#006837") ,
pal <- colorBin(palette = pal8, domain = NULL, bins=quantile(nhmap$Per), na.color = "#808080", alpha = FALSE, reverse = F)) %>%
addProviderTiles("CartoDB.Positron") %>%
clearControls() %>%
clearShapes()%>%
addPolygons(fillColor = ~pal(Per),
stroke=T,
weight=1,
smoothFactor=0.2,
fillOpacity = 1,
color="black",
popup=~paste(NAME,"<br>",input$sex_map,
input$Age_Group_map,"=",Per,"%"),
highlightOptions = highlightOptions(color = "red",
weight = T,
bringToFront = T),
label=~NAME) %>%
addTiles() %>%
setView(-82.706838, 40.358615, zoom=7) %>%
addLegend(position = "bottomright",
values = ~Per,
pal = pal,
title = (paste("%",input$Age_Group_map, input$sex_map, "in", input$Year_map)) ,
labFormat = labelFormat(
))
})
}
shinyApp(ui = ui, server = server)
You have to define the bins in colorBin, at which you want to cut the data in the different color sections. Something like:
pal <- colorBin(palette = pal8, domain = NULL, bins=quantile(mapdata_()$Per),
na.color = "#808080", alpha = FALSE, reverse = F)
And you also have to remove bins= 4 from the addLegend call, as it will get the information from the color palette.
I created some random data for nhmap and it is working for me with this code:
library(shiny)
library(leaflet)
library(sf)
library(sp)
## Random Data #############
data(meuse, package = "sp")
nhmap <- st_as_sf(meuse, coords = c("x", "y"))
st_crs(nhmap) <- "+init=epsg:28992"
nhmap <- st_buffer(nhmap, 100)
n = length(nhmap$cadmium)
nhmap$Age_Group <- sample(c(15,19,25), size = n, T)
nhmap$Sex <- sample(c("m","f"), size = n, T)
nhmap$Per <- runif(n, 1, 150)
nhmap$NAME <- sample(c("a","b","c"), size = n, T)
nhmap$Age_Group <- sample(c(15,19,25), size = n, T)
nhmap$Year <- sample(c(2010,2020,2030, 2040, 2050), size = n, T)
nhmap <- st_transform(nhmap, 4326)
## UI ###########
ui <- {fluidPage(
tabPanel(
"Interactive Maps",
tags$h5 ()),
br(),
sidebarLayout(
sidebarPanel(
selectInput(
inputId = "Age_Group_map",
label = "Select the Age Group:",
# selected = "60+",
selectize = F,
multiple = F,
choices = sort(unique(nhmap$Age_Group))
),
radioButtons(
inputId = "sex_map",
label = strong("Select Sex:"),
# selected = "Both Sexes",
choices = sort(unique(nhmap$Sex))
),
sliderInput(
inputId = "Year_map",
label = "Year",
min = 2010,
max = 2050,
value = 2010,
step = 10,
sep = "",
pre = "",
animate = animationOptions(
interval = 1000,
loop = F,
playButton = tags$button("Play", style =
"background-color: #B61E2E ; color:white; margin-top: 10px; border:solid"),
pauseButton = tags$button("Pause", style =
"background-color: #B61E2E !important; color:white; margin-top: 10px; border:solid")
),
round = T,
width = "150%",
ticks = T
)),
mainPanel("Interactive", leafletOutput("int_map", height=500)))
)}
## SERVER ###########
server <- function(input, output) {
mapdata_ <- reactive ({
nhmap$Per <- round(nhmap$Per, 1)
# nhmap
nhmap %>%
filter (
Age_Group %in% input$Age_Group_map,
Sex %in% input$sex_map,
Year %in% input$Year_map)
})
output$int_map <- renderLeaflet ({
req(mapdata_())
pal8 <- c("#FFFFE5", "#D9F0A3", "#78C679", "#006837")
# pal <- colorBin(palette = pal8, domain = NULL, bins=quantile(mapdata_()$Per),
pal <- colorBin(palette = pal8, domain = NULL, bins=quantile(nhmap$Per),
na.color = "#808080", alpha = FALSE, reverse = F)
leaflet(data = mapdata_()) %>%
# leaflet(data = nhmap) %>%
clearControls() %>%
clearShapes()%>%
addProviderTiles("CartoDB.Positron") %>%
addTiles() %>%
addPolygons(fillColor = ~pal(Per),
stroke=T,
weight=1,
smoothFactor=0.2,
fillOpacity = 1,
color="black",
label=~NAME,
popup=~paste(NAME,"<br>",input$sex_map,
input$Age_Group_map,"=",Per,"%"),
highlightOptions = highlightOptions(color = "red",
weight = T,
bringToFront = T)) %>%
# setView(-82.706838, 40.358615, zoom=7) %>%
addLegend(position = "bottomright",
values = ~Per,
title = (paste("%",input$Age_Group_map, input$sex_map, "in", input$Year_map)),
pal = pal
)
})
}
shinyApp(ui = ui, server = server)
Here is the answer. As I mentioned in my the last comment, the pal needs to be reactive:
mapdata_ <- reactive ({
nhmap$Per <- round(nhmap$Per, 1)
out_map <- nhmap %>%
filter (
Age_Group %in% input$Age_Group_map,
Sex %in% input$sex_map,
Year %in% input$Year_map)
return(out_map)
list(Per)
})
mapdata_1 <- reactive ({
nhmap$Per <- round(nhmap$Per, 1)
out_map_1 <- nhmap %>%
filter (
Age_Group %in% input$Age_Group_map
)
return(out_map_1)
list(Per)
})
output$int_map <- renderLeaflet ({
pal8 <- c("#FFFFE5", "#D9F0A3", "#78C679", "#006837")
pal <- colorBin(palette = pal8, domain =NULL, bins=quantile(mapdata_1()$Per), na.color = "#808080", alpha = FALSE, reverse = F)
leaflet (mapdata_()) %>%
addProviderTiles("CartoDB.Positron") %>%
clearControls() %>%
clearShapes()%>%
addPolygons(fillColor = ~pal(Per),
stroke=T,
weight=1,
smoothFactor=0.2,
fillOpacity = 1,
color="black",
popup=~paste(NAME,"<br>",input$sex_map,
input$Age_Group_map,"=",Per,"%"),
highlightOptions = highlightOptions(color = "red",
weight = T,
bringToFront = T),
label=~NAME) %>%
addTiles() %>%
setView(-82.706838, 40.358615, zoom=7) %>%
addLegend(position = "bottomright",
values = ~Per,
pal = pal,
title = (paste("%",input$Age_Group_map, input$sex_map, "in", input$Year_map)) ,
labFormat = labelFormat(
))
})
I'm building a shiny app and I'm having some trouble with the plotly map event data. I have created a plotly scatterplot in the past and defined a 'key' variable within the plot_ly function. If I clicked on a point in the scatterplot, the key would be extracted and the key would be used to subset a dataframe and produce a subsequent plot. I'm following the same format in the code below, but the key isn't being stored in the event data. The event data only contains the 'curveNumber' and the 'pointNumber'. It seems to work for the choropleth map found here: https://plot.ly/r/shinyapp-map-click/ but I can't get it to work for 'scattergeo'.
Any help would be greatly appreciated.
library(shiny)
library(plotly)
ui <- shinyUI(fluidPage(
titlePanel("My Shiny App"),
sidebarLayout(
sidebarPanel(
numericInput("idnum", label = h3("ID #"),
value = 3)
),
mainPanel(
plotlyOutput("map"),
verbatimTextOutput("click")
)
)
))
server <- shinyServer(function(input, output) {
output$map <- renderPlotly({
df <- data.frame(id = c(3,6,20,35), lat = c(30.67,32.46,37.83,29.62), lon = c(-97.82, -62.34, -75.67, -85.62))
sub <- df[which(df$id == input$idnum),]
g <- 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 = "miller",
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(20, 60),
dtick = 5
)
)
plot_ly(sub, lon = ~lon, lat = ~lat, key = ~id, text = ~paste(id), hoverinfo = "text",
marker = list(size = 10),
type = 'scattergeo',
locationmode = 'USA-states') %>%
layout(title = 'Locations', geo = g)
})
output$click <- renderPrint({
d <- event_data("plotly_click")
if (is.null(d)) "Click events appear here" else d
})
})
shinyApp(ui = ui, server = server)
A workaround to get your key is to replace:
sub <- df[which(df$id == input$idnum),]
with
sub <- df[which(df$id == input$idnum),]
rownames(sub) <- sub$id
key <- row.names(sub)
it looks like key is working with rownames.