我在尝试让动态 UI 与 googlevis 一起使用时遇到了一些问题。本质上,我希望允许用户使用滑块输入感兴趣的范围,并相应地更改绘图。在以下示例中,我使用了 googlevis 包中的数据集来说明我的意思。如果您运行下面的代码,您将不会收到任何错误,但是不会产生任何图:
用户界面
library(shiny)
shinyUI(fluidPage(
titlePanel("Example"),
sidebarLayout(
sidebarPanel(
radioButtons('data_choice', 'choose a dataset',
choices= c('dataset1', 'dataset2')),
uiOutput('slider')
),
mainPanel(
htmlOutput('view')
)
)
))
服务器.R
library(shiny)
library(googleVis)
library(ggplot2)
dataset1= dino
dataset2= Fruits[,c(1,6)]
shinyServer(function(input, output) {
#Output new slider depending on dataset chosen
output$slider<- renderUI({
if(input$data_choice== 'dataset1'){
sliderInput('rangeSlider', 'Choose data range',
min= 0, max= max(dataset1$Length),
value= c(0, max(dataset1$Length)))
}else if(input$data_choice== 'dataset2'){
sliderInput('rangeSlider', 'Choose data range',
min= 0, max= max(dataset2$Profit),
value= c(0, max(dataset2$Profit)))
}
})
#plot adjust
adjustPlot<- reactive({
#Adjust dataframes based on input from slider
if(input$data_choice== 'dataset1'){
adjusted_dataset1<- subset(dataset1,
Length >= input$rangeSlider[1] & Length <= input$rangeSlider[2])
}else if(input$data_choice== 'dataset2'){
adjusted_dataset2<- subset(dataset2,
Profit >= input$rangeSlider[1] & Profit <= input$rangeSlider[2])
}
})
output$view <- renderGvis({
gvisBarChart(adjustPlot(), options= list(height= 700))
})
})
如果您用 ggplot 图而不是 googlevis 替换输出,则代码运行良好。
用户界面
mainPanel(
plotOutput('view')
)
服务器.R
#ggplot that works
output$view <- renderPlot({
if(input$data_choice=='dataset1'){
p<-ggplot(adjustPlot(), aes(x=Dinosaur, y=Length))
p<-p + geom_bar(stat='identity', fill='navyblue') + coord_flip()
}else if(input$data_choice=='dataset2') {
p<-ggplot(adjustPlot(), aes(x=Fruit, y=Profit))
p<-p + geom_bar(stat='identity', fill= 'forestgreen') + coord_flip()
}
print(p)
}, height=550)
当从 renderUI 获取输入时,似乎将谷歌绘图渲染到应用程序时存在问题(可能是因为它将其呈现为 html ..)。任何帮助将不胜感激。谢谢!