我有一个像这样的绘图。在这里,我将添加一个daterange输入。基于此选择,我需要重新绘制图形。
样本数据
dates ex act
NOV-17 77 90
DEC-17 98 78
JAN-18 65 87
FEB-18 77 54
MAR-18 44 34
示例代码:
age <- plot_ly(data_, x = ~dates, y = ~ex, name = 'Expect', type = 'scatter',mode = 'lines+markers',
line = list(color = 'rgb(205, 12, 24)', width = 4)) %>%
add_trace(y =~act , name = 'Actual',mode = 'lines+markers', line = list(color = 'rgb(170, 255, 102)', width = 4)) %>%
layout(title = "Mon vs KM",
xaxis = list(title = "Mon"),
yaxis = list (title = "KM"),
legend = list(orientation = 'h'))
如果我的选择是2017-12-01 to 2018-03-01
,那么我的X轴应该来自DEC-17 to MAR-18
我知道编码,我只需要知道如何过滤x轴
答案 0 :(得分:1)
这是一个有效的示例:
PS:由于月份名称的缩写是特定于语言环境的,因此应谨慎使用。
library(shiny)
library(plotly)
ui <- fluidPage(
titlePanel("Plotly - dateRangeInput"),
sidebarLayout(
sidebarPanel(
dateRangeInput(inputId="myDateRange", label="", start = NULL, end = NULL, min = NULL, max = NULL)
),
mainPanel(
plotlyOutput("age")
)
)
)
server <- function(input, output, session) {
data_ <- data.frame(stringsAsFactors=FALSE,
dates = c("NOV-17", "DEC-17", "JAN-18", "FEB-18", "MAR-18"),
ex = c(77L, 98L, 65L, 77L, 44L),
act = c(90L, 78L, 87L, 54L, 34L))
data_$helperDates <- as.Date(paste0(data_$dates, "-01"), format="%b-%y-%d")
data_ <- data_[order(data_$helperDates, decreasing = FALSE), ]
data_$dates <- factor(data_$dates, levels = c(as.character(data_$dates)))
minDate <- min(data_$helperDates, na.rm = TRUE)
maxDate <- max(data_$helperDates, na.rm = TRUE)
updateDateRangeInput(session, inputId="myDateRange", start = minDate, end = maxDate, min = minDate, max = maxDate)
filteredData <- reactive({
req(input$myDateRange)
na.omit(data_[data_$helperDates >= input$myDateRange[1] & data_$helperDates <= input$myDateRange[2], ])
})
output$age <- renderPlotly({
req({nrow(filteredData()) > 0})
age <- plot_ly(filteredData(), x = ~dates, y = ~ex, name = 'Expect', type = 'scatter', mode = 'lines+markers',
line = list(color = 'rgb(205, 12, 24)', width = 4)) %>%
add_trace(y =~act, name = 'Actual', mode = 'lines+markers', line = list(color = 'rgb(170, 255, 102)', width = 4)) %>%
layout(title = "Mon vs KM",
xaxis = list(title = "Mon"),
yaxis = list (title = "KM"),
legend = list(orientation = 'h'))
})
}
shinyApp(ui = ui, server = server)