我已经在shiny中设置了一个折线图。X轴的日期从2014年到当前日期。
我已经使用geom_vline()设置了各种垂直线来突出显示数据中的点。
我使用dateRangeInput(),这样用户就可以选择要在图形上查看的开始/结束日期范围。
我的其中一条垂直线是在2014年2月。如果用户使用dateRangeInput()来查看2016年1月的日期,那么2014年2月的垂直线仍然显示在图表上。这也导致x轴从2014年开始移动,即使数据线是从2016年1月到当前日期。
当这条垂直线在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)

发布于 2018-08-09 21:51:01
正如Aimée在另一个线程中提到的:
简而言之,除非您另行指定,否则ggplot2将始终绘制您提供的所有数据,并且轴限制基于此。因此,因为您告诉它绘制线和标签,所以它们将出现在图上,即使其余的数据没有扩展到那么远。您可以通过使用coord_cartesian函数告诉ggplot2您希望x轴的限制是什么来解决此问题。
# Set the upper and lower limit for the x axis
dateRange <- c(input$date[1], input$date[2])
my_graph <- ggplot(df, 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") +
coord_cartesian(xlim = dateRange)https://stackoverflow.com/questions/51683989
复制相似问题