gpt4 book ai didi

r - Shiny 的 plotOutput 动态属性

转载 作者:行者123 更新时间:2023-12-04 15:53:00 24 4
gpt4 key购买 nike

我有一个取决于用户输入的情节。
根据输入,绘图大小会有所不同。

我可以动态控制情节的高度吗?
我知道在 plotOutput()我有一个高度参数,但我找不到动态更改它的方法。

可重现的例子,当你选择 A 时,情节看起来不错,但如果你选择 B,那就太高了——

library(shiny)
library(ggplot2)

df1 <- data.frame(x = 1:2000, y = rnorm(2000), type = rep(LETTERS[1:8], 250))
df2 <- data.frame(x = 1:100, y = rexp (100), type = rep(c('A','B'), 50))

ui <- shinyUI(fluidPage(title = '',
fluidRow(selectInput("table",'', choices = c('A','B'))),
fluidRow(plotOutput("my_plot", height = '1000px'))
)
)

server <- shinyServer(function(input, output) {
output$my_plot <- renderPlot({
t <- if(input$table == 'A') df1
else df2
ggplot(t) + facet_grid(type~.) +
geom_point(mapping = aes(x=x, y=y))
}
)
})
shinyApp(ui, server)

最后一件事,在真实的应用程序中,并不是我有 2 种不同的尺寸,这取决于输入的尺寸需要改变。

最佳答案

为了做你需要的,你需要使用服务器端渲染。 UI 不知道情节有什么以及如何动态调整任何内容。它只需要服务器生成的内容并将其显示在屏幕上。

这是一段可以执行的代码(我认为您需要什么)。顺便说一句 - 我还将“数据”部分放入它自己的 react 函数中。您可以进一步修改我的代码,使像素高度“计算”与硬编码等。

library(shiny)
library(ggplot2)

df1 <- data.frame(x = 1:2000, y = rnorm(2000), type = rep(LETTERS[1:8], 250))
df2 <- data.frame(x = 1:100, y = rexp (100), type = rep(c('A','B'), 50))

ui <- shinyUI(fluidPage(title = '',
fluidRow(selectInput("table",'', choices = c('A','B'))),
fluidRow(uiOutput('myPlotUI'))
)
)

server <- shinyServer(function(input, output) {
myData <- reactive({
if (input$table == 'A')
df1
else
df2
})
myPlot <- reactive({
output$myPlot <- renderPlot({
ggplot(myData()) + facet_grid(type~.) +
geom_point(mapping = aes(x=x, y=y))
})
if (input$table == 'A') {
plotOutput('myPlot', height = '1000px')
} else {
plotOutput('myPlot', height = '250px')
}
})
output$myPlotUI <- renderUI({
myPlot()
})
})
shinyApp(ui, server)

关于r - Shiny 的 plotOutput 动态属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41120696/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com