【发布时间】:2020-07-22 13:56:34
【问题描述】:
我正在使用 R Shiny 中的 ggplot 创建交互式折线图。我这样做的方式是让用户在 UI 中使用选择器输入选择他们想要在图中看到的值。然后在服务器中根据用户的选择过滤数据。我使用scale_x_continuous 在ggplot 中指定了x 轴。我将序列设置为 0 到 24 之间的间隔为 1。但是,当用户选择 1-10 时,x 轴将更改为仅显示 1-10。
无论用户选择什么,我都希望 x 轴保持 0 到 24。有没有办法做到这一点?解决方案是否会以不同的方式限制指定ggplot x 轴限制,或者我如何使用选择器输入来过滤数据?
谢谢!
如果有帮助,这是我的代码:
library(shiny)
library(tidyverse)
library(shinyWidgets)
# Create sample dataset and name bin
set.seed(1234)
hour <- sample(1:24, size=100, replace=TRUE)
calls <- sample(1:55, size=100, replace =TRUE)
mydata <- data.frame(hour,calls)
name <- mydata %>%
group_by(hour) %>%
summarize(n())
name_bin <- as.data.frame(name$hour)
ui <- fluidPage(
h1 ("R shiny ggplot Question"),
pickerInput(
inputId = "myPicker",
label = "Select Hour in the day",
choices = name_bin,
options = list(
`actions-box` = TRUE,
size = 10,
`selected-text-format` = "count > 3"),
multiple = TRUE),
box(
width = 11,
plotOutput("graph1"))
)
server <- function(input,output,session) {
output$graph1 <- renderPlot({
g1 <- dplyr::filter(mydata,hour %in% input$myPicker)
g2 <- g1 %>%
group_by(hour) %>%
summarize(number = n())
ggplot(g2, aes(x=hour, y=number)) +
geom_line(color = 'darkblue') + geom_point() +
scale_x_continuous(breaks = seq(0,24, by=1)) + ###### Better way to set x-limits?
scale_y_continuous(breaks = seq(0, max(g2$number), by=5))+
theme_minimal()+
labs(y="Number of Calls", x="Hour in the day",title = "")
})
}
shinyApp(ui, server)
【问题讨论】: