【发布时间】:2018-08-02 01:53:39
【问题描述】:
我有一个 selectInput 用于在 sidebarPanel( 或 fluidRow(column(4,) ) 中指定 sliderInput。sliderInput 从数据集中获取其最小值和最大值,并用于指定图形。由于数据不是等距的,可以选择没有数据的间隔。我想要一个很好的方法来显示数据的位置。下面我做了一些示例代码(没有所需的图表)并附上了一张图片我想要什么(或认为我想要。我愿意接受建议)。我尝试在滑块下摆弄一个流畅的行和 renderPlot,但我没有设法让它们对齐。(这样布局仍然看起来不错当浏览器重新缩放时)。 最好我希望新图是 ggplot2。
更新
已根据 divibisan 的建议更新了代码。我仍然无法正确对齐。
library(shiny)
library(ggplot2)
# data
df = data.frame("sub1" = c(1,10), "sub2" = c(5,90))
sub1_val = data.frame("x" = c(seq(1,4),seq(9,10)), "y" = rnorm(6))
sub2_val = data.frame("x" = c(seq(5,40),seq(85,90)), "y" = rnorm(42))
#
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
fluidRow(
selectInput("sel",label = "Choose subject",
choices = names(df),
selected = "sub2")
,uiOutput("subjectUI")
),
plotOutput("selPlot", width = "75%", height = "100px")
),
mainPanel(
h1("Let there be stuff"),
plotOutput("plot")
)
)
)
server <- function(input, output,session) {
output$subjectUI <- renderUI({
sliderInput("slide","This is a slide",
min = df[input$sel][1,],
max = df[input$sel][2,],
value = c(min,max),
width = "75%"
)
})
output$selPlot <- renderPlot({
switch(input$sel,
"sub1" = if(!is.null(input$slide[2])){plotData = data.frame(xVar = seq(df[input$sel][1,],df[input$sel][2,]));plotData["yVar"] = 1*(plotData$xVar %in% sub1_val$x) },
"sub2" = if(!is.null(input$slide[2])){plotData = data.frame(xVar = seq(df[input$sel][1,],df[input$sel][2,]));plotData["yVar"] = 1*(plotData$xVar %in% sub2_val$x) })
if(!is.null(input$slide[2])){
ggplot(data = plotData, aes(x = xVar, y = yVar)) +
geom_point() + geom_line() +
geom_vline(xintercept = input$slide[1]) +
geom_vline(xintercept = input$slide[2]) +
labs(x = "", y="") +
scale_x_continuous(expand=c(0,0)) +
theme(axis.title.y = element_blank(),
axis.text.y = element_blank(),
axis.ticks.y = element_blank())
}
})
#
output$plot <- renderPlot(
switch(input$sel,
"sub1" = if(!is.null(input$slide[2])){vec = sub1_val$x>= input$slide[1] & sub1_val$x <= input$slide[2];plot(sub1_val$x[vec],sub1_val$y[vec],type ="b")},
"sub2" = if(!is.null(input$slide[1])){vec = sub2_val$x>= input$slide[1] & sub2_val$x <= input$slide[2];plot(sub2_val$x[vec],sub2_val$y[vec],type ="b")}
)
)
}
shinyApp(ui = ui, server = server)
【问题讨论】:
标签: shiny