Hi M_AcostaCH!
Since this seems like it is just for fun, Below will run and should open up some doors for you regarding reactive components in the app, and styling ggplots . Cheers!
library(shiny)
library(leaflet)
library(ggplot2)
library(tidyverse)
lat <- 41.61
long <- 21.21
ui <- fluidPage(
titlePanel("Mapa y gráfica interactiva"),
sidebarLayout(
sidebarPanel(
selectInput("var", "Selecciona una variable:", choices = NULL),
wellPanel(style = 'height: 400px; overflow-y:scroll;',
checkboxGroupInput("mdl", "Selecciona una Modelo:", choices = NULL,
selected = NULL, inline = TRUE)
),
sliderInput("range", "Rango:", min = 0, max = 500, value = c(0, 500), step = 10)
),
mainPanel(
h2('Map of Something'),
leafletOutput("map"),
h2('Compare Vehicles'),
plotOutput("plot")
)
)
)
# Define server
server <- function(input, output, session) {
# Get data to long format
data <- reactive({
mtcars %>%
as.data.frame() %>%
mutate(Model = row.names(.)) %>%
pivot_longer(., cols = !Model,names_to = "Parameter", values_to = "Value")
})
# Update selectInputs since they start blank
observe({
if(length(input$mdl) == 0 || is.null(input$mdl)){
updateCheckboxGroupInput(session = session, inputId = 'mdl',
choices = unique(data()$Model %>% sort()),
selected = unique(data()$Model %>% sort())
)
}
if(input$var == ""){
updateSelectInput(session = session, inputId = 'var',
choices = unique(data()$Parameter) %>% sort(),
selected = unique(data()$Parameter) %>% sort() %>% .[1]
)
}
if(nrow(pdata) > 0 & !is.null(input$mdl)){
#browser()
vals <- isolate(data()) %>% filter(Model %in% input$mdl, Parameter == input$var) %>% pull(Value)
updateSliderInput(session = session, inputId = 'range',
min = min(vals),
max = max(vals),
value = c(min(vals), max(vals))
)
}
})
# Mapa
output$map <- renderLeaflet({
leaflet(mtcars) %>%
addTiles() %>%
addMarkers(lat = ~lat, lng = ~long, popup = ~paste("Modelo: ", rownames(mtcars)))
})
# Gráfica
# output$plot <- renderPlot({
# ggplot(data = mtcars, aes_string(x = input$var)) +
# geom_histogram(binwidth = 1, fill = "steelblue", col = "black") +
# xlim(input$range)
# })
output$plot <- renderPlot({
if(is.null(input$mdl)){return(NULL)}
if(!is.null(input$mdl) & length(input$mdl) > 1){
pdata <- data() %>%
filter(Parameter == input$var,
Model %in% input$mdl,
Value >= input$range[1] & Value <= input$range[2]
) %>%
as.data.frame()
} else {
return(NULL)
}
ggplot(data = pdata, aes(x = Model, y = Value, fill = Model)) +
geom_bar(stat = 'identity', color = 'black') +
labs(title = 'Vehicle Parameters by Model', x = 'Model', y = input$var) +
theme(
legend.title = element_blank(),
axis.text.x = element_text(angle = 90)
)
})
}
# Run app
shinyApp(ui, server)