I am trying to use shinyApp with the leaflet package. I have tried using the "SelectInput" function in the dashboard to create a reactive map based on the input selected(country).However, I am not able to make the leaflet and the SelectInput connect with each other.
Here is my code:
library(shiny)
library(leaflet)
ui <- (fluidPage(
titlePanel(title = "Pig breeding countries in 2000 - Top 5"),
sidebarLayout(
sidebarPanel(
selectInput(inputId = "country",
label = "Select a country to view it's values (you can choose more than one):",
c("Brazil", "China", "Russia", "USA", "Vietnam"), multiple = TRUE
)
),
#mainPanel must be outside the sidebarLayout argument
mainPanel(leafletOutput("mymap", height = "500"),
leafletOutput("country")
))
)
)
server <- (function(input, output){
output$mymap <- renderLeaflet(input$country)
output$mymap <- renderLeaflet({
mymap = leaflet()
setView(mymap, lng = -16.882374406249937, lat = -1.7206857960062047, zoom = 0)
mymap = addProviderTiles(mymap, provider = "CartoDB.Positron")
mymap = addMarkers(mymap,lng = 101.901875, lat = 35.486703, popup = "China 35,500")
mymap = addMarkers(mymap,lng = -95.712891, lat = 37.090240, popup = "USA 6,267")
mymap = addMarkers(mymap,lng = 108.339537, lat = 14.315424, popup = "Vietnam 2,947")
mymap = addMarkers(mymap,lng = 37.618423, lat = 55.751244, popup = "Russia 3,070")
mymap = addMarkers(mymap,lng = -46.625290, lat = -23.533773, popup = "Brazil 3,020")}
})
shinyApp(ui, server)
Can someone advise how to link them?
There is no reactive environment between your drop-down selection and leaflet map in your code. Check in the below code to create reactive leaflet map.
library(shiny)
library(leaflet)
df <- read.csv("leaflet.csv")
ui <- (fluidPage(
titlePanel(title = "Pig breeding countries in 2000 - Top 5"),
sidebarLayout(
sidebarPanel( uiOutput("countrynames")
),
mainPanel(leafletOutput("mymap", height = "500")
))
)
)
server <- function(input, output){
output$countrynames <- renderUI({
selectInput(inputId = "country", label = "Select a country to view it's values (you can choose more than one):",
c(as.character(df$country)))
})
map_data <- reactive({
data <- data.frame(df[df$country == input$country,])
data$popup <- paste0(data$country, " ", data$number)
return(data)
})
output$mymap <- renderLeaflet({
leaflet(data = map_data()) %>%
# setView( lng = -16.882374406249937, lat = -1.7206857960062047, zoom = 0) %>%
addProviderTiles( provider = "CartoDB.Positron") %>%
addMarkers(lng = ~lng, lat = ~lat, popup = ~popup)
# addCircles(lng = ~lng, lat = ~lat, popup = ~popup)
})
}
shinyApp(ui, server)
Below is the csv file i have imported in code.
structure(list(lng = c(101.901875, -95.712891, 108.339537, 37.618423
), lat = c(35.486703, 37.09024, 14.315424, 55.751244), country = structure(c(1L,
3L, 4L, 2L), .Label = c("China", "Russia", "USA", "Vietnam"), class = "factor"),
number = c(35500L, 6267L, 2947L, 3070L)), .Names = c("lng",
"lat", "country", "number"), class = "data.frame", row.names = c(NA,
-4L))
Related
Does anyone know if it is possible to initialize the filters defined in the selectizeGroupUI with the first value in each of the filters? Something like the "selected" option in the selectInput. Let's say I have the following code:
if (interactive()) {
library(shiny)
library(shinyWidgets)
data("mpg", package = "ggplot2")
ui <- fluidPage(
fluidRow(
column(
width = 10, offset = 1,
tags$h3("Filter data with selectize group"),
panel(
pickerInput(
inputId = "car_select",
choices = unique(mpg$manufacturer),
options = list(
`live-search` = TRUE,
title = "None selected"
)
),
selectizeGroupUI(
id = "my-filters",
params = list(
manufacturer = list(inputId = "manufacturer", title = "Manufacturer:"),
model = list(inputId = "model", title = "Model:"),
trans = list(inputId = "trans", title = "Trans:"),
class = list(inputId = "class", title = "Class:")
)
),
status = "primary"
),
DT::dataTableOutput(outputId = "table")
)
)
)
server <- function(input, output, session) {
mpg_filter <- reactive({
subset(mpg, manufacturer %in% input$car_select)
})
res_mod <- callModule(
module = selectizeGroupServer,
id = "my-filters",
data = mpg_filter,
vars = c("manufacturer", "model", "trans", "class")
)
output$table <- DT::renderDataTable({
req(res_mod())
res_mod()
})
}
shinyApp(ui, server)
}
If I select "audi" in the pickerInput, is it possible that instantly the filters of "Manufacturer", "Model", "Trans" and "Class" take the value of the first option they have?
I tried to assign a value to the filter with input[["my-filters-model"]] but it shows an error that Can't modify read-only reactive value
I am trying to reproduce the decomposed time series plot with highchart.
The result is perfect in the working directory of r but when I put it in r shiny no result comes out.
Here is my code
library(shinyjs)
library(shiny)
library(shinydashboard)
library(highcharter)
library(forecast)
shinyOptions(bslib = TRUE)
bs_global_theme()
bs_theme_base_colors(bg = "#002B36", fg = "#EEE8D5")
bs_theme_accent_colors(primary = "#2AA198")
thematic::thematic_shiny()
ui<-fluidPage(
theme=shinytheme("cerulean"),
themeSelector(),
useShinyjs(),
navbarPage(
title= "Stock exchange", position = "static-top",
id="nav",
tabPanel("Single stock analysis",value = "single_stock", icon = icon("chart-area"),
sidebarLayout(
div(id = "Sidebar",
sidebarPanel(width = 3, align = "center",
selectInput("ticker",
strong("Ticker"),
# quotes$Symbole,
choices = c("AirPassengers", "ttrc"),
selectize = TRUE
),
dateRangeInput("date", strong("Select data range"),
start = "2012-01-01", end = (Sys.Date()-1)
),
tags$br(),
fluidPage(column(width = 3, "Session")
)
)),
mainPanel(
fluidRow(align = "center",
selectInput("hideorshow", label = strong("Sidebar disposition"),
choices = c("Show", "Hide"), selected = "Show")),
tabsetPanel(
tabPanel("Data structure and summary",
icon = icon("table"),
h1(align = "center",
strong(" STRUCTURE OF THE DATAFRAME ")),
tags$br(),tags$b(),class="fa fa-table",
verbatimTextOutput("struc"),
tags$br(),tags$br(),
h1(align = "center",strong(" SUMMARY OF THE DATAFRAME ")),
br(),verbatimTextOutput("summary1")
),
tabPanel("Dataset",icon = icon("tablet-alt"), DTOutput('tbl1')),
tabPanel("Plot",icon = shiny::icon('chart-bar'), br(),br(), br(),
airDatepickerInput(inputId = "date.ts",
strong("Time of the first observation"),
value = "2017-01-01",
minDate = "1998-09-16",
maxDate = Sys.Date(),
view = "months",
minView = "months",
dateFormat = "yyyy-mm"),
highchartOutput("closing_pr.ts",width = "auto", height = "600px"),
),
)
)
)),
tabPanel("Multiple stocks analysis", tabName = "mult_stock", icon = icon("th"))
)
)
I think the problem is hide in the server; exactely the renderHighchart but i can't find it. Please any help will be appreciate.
cs <- new.env()
dt_new <- eventReactive(c(input$ticker,input$date[1],input$date[2]), {
if (input$ticker =="AirPassengers"){
data(AirPassengers)
mydata1 <- AirPassengers
}
else if (input$ticker =="ttrc"){
data(ttrc)
mydata1 <- ttrc
}
mydata1
})
output$closing_pr.ts<-renderHighchart({
year.ts <- as.numeric(year(input$date.ts))
month.ts <- as.numeric(month(input$date.ts))
dc <- decompose(AirPassengers)
df <- as.data.frame(dc[c("x","trend","seasonal","random")])
df2 <- data.frame(Date = index(dc$x),
apply(df, 2, as.numeric))
names(df2) <- c("Date", "Observed", "Trend", "Seasonal", "Random")
df2$Date <- as.Date(yearmon(df2$Date))
df2 <- as.xts(df2[,-c(1)],
order.by = df2$Date)
df2 <- round(df2, digits = 3)
highchart(type = "stock") %>%
hc_title(text = "TIME SERIE DECOMPOSITION") %>%
hc_add_series(df2[, "Observed"], yAxis = 0, name = "Observed", showInLegend = FALSE) %>%
hc_add_yAxis(nid = 1L, title = list(text = "Observed"), relative = 2) %>%
hc_add_series(df2[, "Trend"], yAxis = 1, type = "line",name = "Trend", showInLegend = FALSE) %>%
hc_add_yAxis(nid = 2L, title = list(text = "Trend"), relative = 1)%>%
hc_add_series(df2[, "Seasonal"], yAxis = 2, type = "line",name = "Seasonal", showInLegend = FALSE) %>%
hc_add_yAxis(nid = 1L, title = list(text = "Seasonal"), relative = 2) %>%
hc_add_series(df2[, "Random"], yAxis = 3, type = "line", name = "Random", showInLegend = FALSE) %>%
hc_add_yAxis(nid = 2L, title = list(text = "Random"), relative = 1)%>%
hc_exporting(
enabled = TRUE, # always enabled,
filename = paste0("Closing price decomposition line charts from ",
min(index(df2)),
" to ", max(index(df2))))%>%
hc_colors(colors = c("blue", "red", "cyan", "darkgreen"))
})
observeEvent(input$hideorshow, {
if ( input$hideorshow== "Show") {
shinyjs::show(id = "Sidebar")}
else {shinyjs::hide(id = "Sidebar")}
})
output$summary1 <- renderPrint({
summary(dt_new())
})
output$struc<- renderPrint({
str(dt_new())
})
}
shinyApp(ui=ui, server = server)
Try this
library(shinyjs)
library(shiny)
library(shinydashboard)
library(highcharter)
library(forecast)
library(lubridate)
library(zoo)
library(xts)
shinyOptions(bslib = TRUE)
# bs_global_theme()
# bs_theme_base_colors(bg = "#002B36", fg = "#EEE8D5")
# bs_theme_accent_colors(primary = "#2AA198")
# thematic::thematic_shiny()
ui<-fluidPage(
#theme=shinytheme("cerulean"),
#themeSelector(),
useShinyjs(),
navbarPage(
title= "Stock exchange", position = "static-top",
id="nav",
tabPanel("Single stock analysis",value = "single_stock", icon = icon("chart-area"),
sidebarLayout(
div(id = "Sidebar",
sidebarPanel(width = 3, align = "center",
selectInput("ticker",
strong("Ticker"),
# quotes$Symbole,
choices = c("AirPassengers", "ttrc"),
selectize = TRUE
),
dateRangeInput("date", strong("Select data range"),
start = "2012-01-01", end = (Sys.Date()-1)
),
tags$br(),
fluidPage(column(width = 3, "Session")
)
)),
mainPanel(
fluidRow(align = "center",
selectInput("hideorshow", label = strong("Sidebar disposition"),
choices = c("Show", "Hide"), selected = "Show")),
tabsetPanel(
tabPanel("Data structure and summary",
icon = icon("table"),
h1(align = "center",
strong(" STRUCTURE OF THE DATAFRAME ")),
tags$br(),tags$b(),class="fa fa-table",
verbatimTextOutput("struc"),
tags$br(),tags$br(),
h1(align = "center",strong(" SUMMARY OF THE DATAFRAME ")),
br(),verbatimTextOutput("summary1")
),
tabPanel("Dataset",icon = icon("tablet-alt"), DTOutput('tbl1')),
tabPanel("Plot",icon = shiny::icon('chart-bar'), br(),br(), br(),
airDatepickerInput(inputId = "date.ts",
strong("Time of the first observation"),
value = "2017-01-01",
minDate = "1998-09-16",
maxDate = Sys.Date(),
view = "months",
minView = "months",
dateFormat = "yyyy-mm"),
highchartOutput("closing_prts",width = "auto", height = "600px"),
),
)
)
)),
tabPanel("Multiple stocks analysis", tabName = "mult_stock", icon = icon("th"))
)
)
server <- function(input, output, session){
cs <- new.env()
# dt_new <- eventReactive(c(input$ticker,input$date[1],input$date[2]), {
dt_new <- reactive({
if (input$ticker =="AirPassengers"){
data(AirPassengers)
print("Hello")
mydata1 <- AirPassengers
} else if (input$ticker =="ttrc"){
data(ttrc)
mydata1 <- ttrc
}
as.data.frame(mydata1)
})
df1 <- reactive({
year.ts <- as.numeric(year(input$date.ts))
month.ts <- as.numeric(month(input$date.ts))
dc <- decompose(AirPassengers)
df <- as.data.frame(dc[c("x","trend","seasonal","random")])
df2 <- data.frame(Date = index(dc$x),
apply(df, 2, as.numeric))
names(df2) <- c("Date", "Observed", "Trend", "Seasonal", "Random")
df2$Date <- as.Date(yearmon(df2$Date))
df2 <- as.xts(df2[,-c(1)],
order.by = df2$Date)
df2 <- round(df2, digits = 3)
df2
})
output$closing_prts <- renderHighchart({
df2 <- df1()
highchart(type = "stock") %>%
hc_title(text = "TIME SERIE DECOMPOSITION") %>%
hc_add_series(df2[, "Observed"], yAxis = 0, name = "Observed", showInLegend = FALSE) %>%
hc_add_yAxis(nid = 1L, title = list(text = "Observed"), relative = 2) %>%
hc_add_series(df2[, "Trend"], yAxis = 1, type = "line",name = "Trend", showInLegend = FALSE) %>%
hc_add_yAxis(nid = 2L, title = list(text = "Trend"), relative = 1)%>%
hc_add_series(df2[, "Seasonal"], yAxis = 2, type = "line",name = "Seasonal", showInLegend = FALSE) %>%
hc_add_yAxis(nid = 1L, title = list(text = "Seasonal"), relative = 2) %>%
hc_add_series(df2[, "Random"], yAxis = 3, type = "line", name = "Random", showInLegend = FALSE) %>%
hc_add_yAxis(nid = 2L, title = list(text = "Random"), relative = 1)%>%
hc_exporting(
enabled = TRUE, # always enabled,
filename = paste0("Closing price decomposition line charts from ",
min(index(df2)),
" to ", max(index(df2))))%>%
hc_colors(colors = c("blue", "red", "cyan", "darkgreen"))
})
observeEvent(input$hideorshow, {
if ( input$hideorshow== "Show") {
shinyjs::show(id = "Sidebar")}
else {shinyjs::hide(id = "Sidebar")}
})
output$tbl1 <- renderDT({datatable(dt_new())})
output$summary1 <- renderPrint({
summary(dt_new())
})
output$struc<- renderPrint({
str(dt_new())
})
}
shinyApp(ui, server)
I am hoping for some help. I am the newest of the newbees and attempting to make this code work utilizing ShinyApp. Upon running my codes, I am receiving the error message of:
Warning: Error in $<-.data.frame: replacement has 0 rows, data has 1352
Is there anything that appears incorrect with my code that stands out? or any suggestions on next tries?
ui.R Code
library(shiny)
library(plotly)
library(DT)
mobility <- read.csv("mobility_data.csv", sep = ',')
mobility$Date <- as.Date(mobility$Date, format="%m/%d/%Y")
mobility$Province <- as.factor(mobility$Province)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
h2("COVID-19 Mobility Data"),
selectInput(inputId = "dv", label = "Category",
choices = c("Retail_Recreation", "Grocery_Pharmarcy", "Parks", "Transit_Stations", "Workplaces", "Residential"),
selected = "Grocery_Pharmarcy"),
selectInput(inputId = "provinces", "Province(s)",
choices = levels(mobility$Province),
multiple = TRUE,
selected = c("Utrecht", "Friesland", "Zeeland")),
dateRangeInput(inputId = "date", label = "Date range",
start = min(mobility$Date),
end = max(mobility$Date)),
downloadButton(outputId = "download_data", label = "Download"),
),
mainPanel(
plotlyOutput(outputId = "plot"),
em("Postive and negative percentages indicate an increase and decrease from the baseline period (median value between January 3 and February 6, 2020) respectively."),
DT::dataTableOutput(outputId = "table")
)
)
)
server.R code
server <- function(input, output) {
filtered_data <- reactive({
subset(mobility,
Province %in% input$provinces &
Date >= input$date[1] & Date <= input$date[2])})
output$plot <- renderPlotly({
ggplotly({
p <- ggplot(filtered_data(), aes_string(x = "Date", y = input$dv, color = "Province")) +
geom_point(alpha = 0.5) + theme(legend.position = "none") + ylab("% change from baseline")
p
})
})
output$table <- DT::renderDataTable({
filtered_data()
})
output$download_data <- downloadHandler(
filename = "Mobility_Data.csv",
content = function(file) {
data <- filtered_data()
write.csv(data, file, row.names = FALSE)
}
)
}
Here is the first seven rows from of sample data from my dataset entitled "mobility_data" as well:
structure(list(Country = c("Netherlands", "Netherlands", "Netherlands",
"Netherlands", "Netherlands", "Netherlands", "Netherlands"),
Province = c("Flevoland", "Flevoland", "Flevoland", "Flevoland",
"Flevoland", "Flevoland", "Flevoland"), Date = c("2/15/2020",
"2/16/2020", "2/17/2020", "2/18/2020", "2/19/2020", "2/20/2020",
"2/21/2020"), Retail_Recreation = c(-2L, -17L, 0L, 6L, 2L,
-2L, 4L), Grocery_Pharmarcy = c(-3L, -13L, -6L, -2L, -7L,
-5L, -1L), Parks = c(4L, -30L, 3L, 30L, 27L, 3L, 21L), Transit_Stations = c(5L,
-9L, -14L, -13L, -15L, -16L, -11L), Workplaces = c(-1L, -7L,
-19L, -18L, -18L, -20L, -21L), Residential = c(0L, 1L, 3L,
3L, 2L, 3L, 2L)), row.names = c(NA, 7L), class = "data.frame")
You can read the csv file using fileInput. Try this
library(shiny)
library(plotly)
library(DT)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
h2("COVID-19 Mobility Data"),
fileInput("file1", "Choose CSV file to upload", accept = ".csv"),
selectInput(inputId = "dv", label = "Category",
choices = c("Retail_Recreation", "Grocery_Pharmarcy", "Parks", "Transit_Stations", "Workplaces", "Residential"),
selected = "Grocery_Pharmarcy"),
selectInput(inputId = "provinces", "Province(s)",
choices = levels(mobility$Province),
multiple = TRUE,
selected = c("Utrecht", "Friesland", "Zeeland")),
dateRangeInput(inputId = "date", label = "Date range",
start = min(mobility$Date),
end = max(mobility$Date)),
downloadButton(outputId = "download_data", label = "Download"),
),
mainPanel(
plotlyOutput(outputId = "plot"),
em("Postive and negative percentages indicate an increase and decrease from the baseline period (median value between January 3 and February 6, 2020) respectively."),
DT::dataTableOutput(outputId = "table")
)
)
)
server <- function(input, output) {
mobility <- reactive({
infile <- input$file1
req(infile)
return(read.csv(infile$datapath, header=TRUE, sep=','))
})
filtered_data <- reactive({
subset(mobility(),
Province %in% input$provinces &
Date >= input$date[1] & Date <= input$date[2])})
output$plot <- renderPlotly({
ggplotly({
p <- ggplot(filtered_data(), aes_string(x = "Date", y = input$dv, color = "Province")) +
geom_point(alpha = 0.5) + theme(legend.position = "none") + ylab("% change from baseline")
p
})
})
output$table <- DT::renderDataTable({
filtered_data()
})
output$download_data <- downloadHandler(
filename = "Mobility_Data.csv",
content = function(file) {
data <- filtered_data()
write.csv(data, file, row.names = FALSE)
}
)
}
shinyApp(ui, server)
I want to fetch user choice from selectInput and store it as a string to be use as filename to save a plot. If user change selectInput choice, the string variable should also update to reflect change.
Here are my code so far and the xxx variable obviously is not a string. Can anyone assist?
pacman::p_load(dplyr, tidyverse, reshape, ggplot2, shiny, shinydashboard)
mtcars_colName <- colnames(mtcars)
x_coord <- mtcars_colName[c(1:2)]
y_coord <- mtcars_colName[c(3:7)]
#Put plots on shiny ui
ui <- dashboardPage(
dashboardHeader(title = 'mtcars data'),
dashboardSidebar(
sidebarMenu(
menuItem("mtcars data comparison", tabName = 'mtcars_data_comparison', icon = icon('dragon'))
)
),
dashboardBody(
tabItems(
tabItem('mtcars_data_comparison',
fluidPage(
downloadButton("downloadPlot", "Download mtcars plot"),
box(plotOutput('metrics_plot'), width = 8, height = '100%'),
box(selectInput('y_metrics', 'mtcars y-axis', choices = y_coord), width = 4),
box(selectInput('x_metrics', 'mtcars x-axis', choices = x_coord), width = 4)
),
)
)
)
)
server <- function(input, output, session){
mtcars_plot <- reactive({ggplot(mtcars, aes_string(x=input$x_metrics, y=input$y_metrics)) +
geom_jitter(width =0.05) +
scale_y_continuous(labels = scales::comma) +
theme(
axis.text.x = element_blank(),
axis.line = element_line(),
axis.ticks.x = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.border = element_blank(),
panel.background = element_blank())
})
output$metrics_plot <- renderPlot({
mtcars_plot()
})
rv <- reactiveValues(value_store = character())
observeEvent(input$y_metrics, {
rv$value_store <- input$y_metrics
})
output$download10XPlot <- downloadHandler(
file = paste(rv$value_store, '.pdf', sep=''),
content = function(file) {
sep <- switch(input$filetype, "csv" = ",", "tsv" = "\t")
# pdf(file = file, width = 11, height = 8.5)
pdf(file, sep = sep)
print(TenX_plot())
dev.off()}
)
}
shinyApp(ui, server)
We can try
output$download10XPlot <- downloadHandler(
file = function() {paste(isolate(input$y_seq_metrics), '.pdf', sep='')},
content = function(file) {
pdf(file = file, width = 11, height = 8.5)
print(TenX_plot())
dev.off()}
)
Here is my problem, I have a couple of tabs and I'm trying to update a map according to a choice in the selectInput() function.
The select option in inputSelect() is activated and points to Los Angeles which should activate the ObserveEvent() or Observe() function but it doesn't when clicking on the Map tab for the first time.
However, I realized that the setView() function doesn't update itself when clicking on the second tab even if I have the selected option set in selectInput().
I want a setView() that reacts to the selected option on the first click on the tab.
The selectize option doesn't bring any difference.
Here is an example of what I would like to replicate.
library(shiny)
library(leaflet)
ui = bs4DashPage(
h1('Exemple'),
br(),
bs4TabSetPanel(id = 'tabs',
side = 'left',
bs4TabPanel(tabName = 'First tab',
active = TRUE,
'Here is some text'),
bs4TabPanel(tabName = 'Second tab',
active = FALSE,
fluidRow(bs4Card(title = 'Inputs',
solidHeader = TRUE,
width = 2,
closable = FALSE,
selectInput(inputId = 'city',
label = 'Select a city',
choices = c('New York','Los Angeles','Seattle'),
selected = 'Los Angeles',
selectize = TRUE)),
bs4Card(title = "Map",
width = 10,
leafletOutput('map'))
)))
)
server <- function(input, output, session) {
output$map <- renderLeaflet({
leaflet() %>%
addTiles() %>%
setView(lng = -95.7129,lat = 37.0902, zoom = 3)
})
observeEvent(input$city, {
if(input$city == 'New York'){
lon <- -74.0060
lat <- 40.7128
} else if(input$city == 'Los Angeles'){
lon <- -118.2437
lat <- 34.0522
} else{
lon <- -122.3321
lat <- 47.6062
}
leafletProxy('map') %>%
setView(lng = lon, lat = lat, zoom = 5)
})
}
shinyApp(ui, server)
Thank you for your help.