Shiny应用输入参数后不显示折线图且触发geom_path缺失值警告如何解决
问题原因
- 日期过滤逻辑错误:
dateRangeInput组件返回的input$fecha本身就是标准Date类型,你额外用as.Date(input$fecha[1], format="%d/%m/%Y")转换属于冗余且错误的操作——format="%d/%m/%Y"会强行把原本格式为yyyy-mm-dd的日期按日月年解析,直接生成错误日期或NA,导致筛选后数据集为空或匹配不到对应数据。 - X轴范围设置完全错误:你的X轴映射的是日期类型,日期在ggplot内部是按1970-01-01为起点的天数存储的,你写的
xlim(-1.5,1.5)等于把X轴限制在1970年1月前后3天的范围,而你的数据全部是2019年及以后的日期,所有数据点都超出绘图范围,所以会触发移除所有行的警告,看不到折线。
解决方案
修改两处代码即可:
- 移除reactive数据筛选环节多余的日期格式转换,直接使用
input$fecha的原生Date值 - 删除ggplot代码中错误的
xlim(-1.5,1.5)行,若需要限制X轴范围可以基于筛选后的日期范围动态设置,或者直接删除让ggplot自动适配范围
另外建议给颜色映射设置命名向量,避免factor顺序变化导致的颜色匹配错误:把scale_color_manual(values=c("blue","red", "pink"))改成scale_color_manual(values = c("cv" = "blue", "sv" = "red", "tot" = "pink")),fill参数同理。
修复后完整代码
library(shiny) # Librería principal library(tidyverse) # Manipulación de datos library(bslib) # Modificación de temas library(thematic) # Ajuste del tema con el plot thematic::thematic_shiny(font = "auto") ui <- fluidPage( theme = bs_theme(version = 4, bootswatch = "minty", heading_font = font_google("Work Sans"), base_font = font_google("Work Sans"), code_font = font_google("Space Mono") ), titlePanel( h4(strong("Robos, 2019-2021"))), sidebarPanel( dateRangeInput("fecha", "Fecha", start= "2019-01-01", end= "2021-05-31", format= "dd/mm/yyyy", separator="-", language= "es" ), # Caja para seleccionar entre opciones checkboxGroupInput("tipo", "Tipo", choices = list("Con violencia" = "cv", "Sin violencia" = "sv", "Total" = "tot"), selected = "tot") ), # Creación de panel donde se colocará el output principal (default lado derecho) mainPanel( # Aquí se puede agregar un título plotOutput("robos") ) ) ) server <- function(input, output) { data <- reactive( { dplyr::filter(delitos, dplyr::between(fecha, input$fecha[1], input$fecha[2]) & tipo %in% input$tipo) }) output$robos <- renderPlot({ ggplot(data(), aes(x=fecha, y=n, color=tipo, fill=tipo)) + geom_line(size=1.2) + xlab("Fecha") + ylab("Robos") + scale_fill_manual(values = c("cv" = "blue", "sv" = "red", "tot" = "pink"))+ scale_color_manual(values = c("cv" = "blue", "sv" = "red", "tot" = "pink")) + theme(legend.title = element_blank()) }) } shinyApp(ui, server)
内容的提问来源于stack exchange,提问作者Alejandro Carrera
相关产品推荐
相关产品推荐

