我想使用R的shiny
包生成一个应用程序。我想从其他项目上传ggplots并添加一些互动内容。
当我使用geom_point()
将数据点添加到在相同R代码中创建的ggplot时,这可以正常工作。但是,当我再次保存并重新读取ggplot(*)时,会发生错误。我仍然可以添加geom_point
(**),但它不接受来自input$slider
的互动内容。
ui.R
library(shiny)
shinyUI(
fluidPage(
# Title
titlePanel(""),
# sidebar
sidebarLayout(
sidebarPanel("",
sliderInput("slider", "slider",
min = 100, max = 500, value = 300, step = 10)
),
# Main
mainPanel("",
plotOutput("ggplt")
)
)
)
)
server.R
library(shiny)
shinyServer(
function(input, output){
# produce a plot
output$ggplt <- renderPlot({
# ggplot scatterplot
library(ggplot2)
gg <- ggplot(data = mtcars, aes(x = disp, y = mpg)) +
geom_point()
# (*) save ggplot
#saveRDS(gg, "plt.rds")
#rm(gg)
#gg <- readRDS("plt.rds")
# x-coordinate for geom_point
xc <- as.numeric(input$slider)
gg + geom_point(aes(x = xc, y = 20), size = 5, colour = "red")
## (**) alternative
#gg + geom_point(aes(x = 400, y = 20), size = 5, colour = "red")
})
}
)
答案 0 :(得分:1)
我真的不知道这里发生了什么,我认为这可能是ggplot2环境处理和闪亮的反应环境处理之间的一些微妙的相互作用。可能值得将其标记为错误。
然而,有很多方法可以使它适用于小的变化。我认为最好的方法是使用反应函数作为滑块值,尽管只在xc
上分配<<-
似乎也有效,并且是一个较小的变化。
您也可以直接在input$slider
函数中使用aes(..)
,因为它似乎也有效,但使用反应函数感觉更干净。
所以这就是我建议的解决方法:
library(shiny)
library(ggplot2)
u <- shinyUI(
fluidPage(
titlePanel(""),
sidebarLayout(
sidebarPanel("", sliderInput("slider", "slider",
min = 100, max = 500, value = 300, step = 10)
),
mainPanel("", plotOutput("ggplt")
)
)))
s <- shinyServer( function(input, output){
sliderval <- reactive({input$slider})
output$ggplt <- renderPlot({
req(input$slider)
gg <- ggplot(data = mtcars) +
geom_point(aes(x = disp, y = mpg))
# (*) save ggplot
saveRDS(gg, "plt.rds")
rm(gg)
gg <- readRDS("plt.rds")
gg + geom_point(aes(x = sliderval(), y = 20), size = 5, colour = "red")
})
})
shinyApp(u,s)
得到以下特性: