我正在试图弄清楚如何在Shiny R包中的renderPlot函数中创建“height”变量从renderPlot()内部接收变量。这是我在server.R中的代码:
shinyServer(function(input, output) {
output$contents <- renderPlot({
file<-input$file #a CSV file is uploaded
file<-with(file,
aggregate(file[, input$metricIn],
by=list(period=day,
dimension1=file[, input$dimension1In],
dimension2=file[, input$dimension2In]),
FUN = input$funIn, na.rm=TRUE))
#input$dimension1In is column name from file
#input$dimension2In is column name from file
#count of facets in the plot to calculate height in renderPlot height argument
facetCount<<-as.numeric(length(unique(file[, input$dimension1In]))) * 100
plot<-reactive({
g<-ggplot(data = file, aes_string(x=input$dimension2In,
y=input$metricIn, fill=period))
plot<-g + geom_bar(stat="identity", position=position_dodge()) +
facet_wrap(as.formula(paste("~", input$dimension1In)),
scales = "free", ncol=1)
}) #end of reactive
print(plot())
}, width=1000,
height = facetCount)
}) #end of shinyServer
所以我的问题是,高度参数是renderPlot,即使我在renderPlot中使用&lt;&lt; - 赋值,也看不到facetCount变量。
我想让高度动态,因为如果要绘制很多方面,我希望绘图高度相应调整。
答案 0 :(得分:2)
当你的情节高度仅取决于某些输入值时,请按照this question的答案。主要更改是在ui.R文件中使用uiOutput
而不是plotOutput
,因此还将plotOutput
中的renderUI
包装在server.R文件中。
如果在服务器端计算绘图的高度,就像上面的示例一样,您还需要在height
中的plotOutput
参数中添加函数调用。我认为这是必需的,因为在制作实际绘图之前Shiny使用了height参数。以下示例对我有用。
ui.R:
shinyUI(fluidPage(
titlePanel("The plot height depends on a calculated value"),
# Sidebar with a slider input for a number
sidebarLayout(
sidebarPanel(
sliderInput("dimension1In",
"Choose a number:",
min = 20,
max = 50,
value = 30)
),
# use uiOutput instead of plotOutput directly
mainPanel(
uiOutput('ui_plot')
)
)
))
server.R:
shinyServer(function(input, output) {
# instead of global assignment use reactive values
values <- reactiveValues()
# function where you do all the processing, e.g. read file, get data from it
file_processing <- function() {
# imagine this coefficient comes from your file
coefficient <- 10
return(coefficient)
}
# this function defines a height of your plot
plot_height <- function() {
# calculate values$facetCount
values$facetCount <- as.numeric(input$dimension1In) * file_processing()
return(values$facetCount)
}
# this function defines your plot, which depends on input$dimension1In
output$contents <- renderPlot({
plot(1:input$dimension1In)
})
# wrap plotOutput in renderUI
output$ui_plot <- renderUI({
plotOutput("contents", height = plot_height(), width = "100%")
})
})