我已经建立了一个闪亮的折线图。x 轴的日期涵盖 2014 年到当前日期。
我已经使用 geom_vline() 设置了各种垂直线来突出显示数据中的点。
我正在使用 dateRangeInput() 以便用户可以选择开始/结束日期范围以查看图表。
我的一条垂直线是 2014 年 2 月。如果用户使用 dateRangeInput() 查看从 2016 年 1 月开始的日期,则 2014 年 2 月的垂直线仍显示在图表上。即使数据线从 2016 年 1 月到当前日期,这也导致 x 轴从 2014 年开始。
当这条垂直线在 dataRangeInput() 之外时,有没有办法阻止它在图表上显示?也许 geom_vline() 中有一个论点来处理这个问题?
library(shiny)
library(tidyr)
library(dplyr)
library(ggplot2)
d <- seq(as.Date("2014-01-01"),Sys.Date(),by="day")
df <- data.frame(date = d , number = seq(1,length(d),by=1))
lines <- data.frame(x = as.Date(c("2014-02-07","2017-10-31", "2017-08-01")),
y = c(2500,5000,7500),
lbl = c("label 1", "label 2", "label 3"))
#UI
ui <- fluidPage(
#date range select:
dateRangeInput(inputId = "date", label = "choose date range",
start = min(df$date), end = max(df$date),
min = min(df$date), max = max(df$date)),
#graph:
plotOutput("line")
)
#SERVER:
server <- function(input, output) {
data <- reactive({ subset(df, date >= input$date[1] & date <= input$date[2])
})
#graph:
output$line <- renderPlot({
my_graph <- ggplot(data(), aes(date, number )) + geom_line() +
geom_vline(data = lines, aes(xintercept = x, color = factor(x) )) +
geom_label(data = lines, aes(x = x, y = y,
label = lbl, colour = factor(x),
fontface = "bold" )) +
scale_color_manual(values=c("#CC0000", "#6699FF", "#99FF66")) +
guides(colour = "none", size = "none")
return(my_graph)
})
}
shinyApp(ui = ui, server = server)