0

我已经建立了一个闪亮的折线图。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)

图表图片:

4

1 回答 1

0

正如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)
于 2018-08-09T13:51:00.510 回答