在 r 中使用闪亮的保存的 ggplot2 图

Using saved ggplot2 figure with shiny in r

我想绘制图形的密度图保存它并在闪亮的应用程序中渲染它。我想动态添加到图中的是来自输入的一行,显示新输入的变量在密度图中的位置:我将 iris 数据中的 ggplot 图保存为:

library(ggplot2)
twoClassIrisSepalLength <- subset(iris[1:100,], select=c("Species","Sepal.Length"))

twoClassIrisSepalLength$Species <- factor(twoClassIrisSepalLength$Species)

g <- ggplot(twoClassIrisSepalLength,aes(x=Sepal.Length, fill=Species)) 
     + geom_density(alpha=0.5) + scale_size_area()  

g <- g+theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), 
axis.text=element_text(size=14),plot.title = element_text(size = rel(1.5), 
colour = "black"),    axis.title=element_text(size=16,face="bold"),
panel.background = element_blank(), axis.line = element_line(colour = "black"),
legend.justification = c(1, 1), legend.position = c(1, 1))

save(g,file="ggplot_sepal_length_density.rda")

当我添加截距时

g <- g+geom_vline(aes(xintercept= 27%%7),  
     colour="#BB0000", linetype="dashed", size=2)

得到我想要的图如下图:

我想在 R shiny 中动态绘制值 6 中的暗红色线。现在 shiny 我的 ui.R 看起来像:

library(ggplot2)
shinyUI(pageWithSidebar(
  headerPanel('Density plots'),
  sidebarPanel(
    numericInput('sepal_length', 'Sepal Length', 3,
                 min = 1, max = 7)
  ),
  mainPanel(
    plotOutput('plot1')
  )
))

我的 server.R

shinyServer(function(input, output, session) {

output$plot1 <- renderPlot({
    load("ggplot_sepal_length_density.rda")

    g <- g+geom_vline(aes(xintercept= as.numeric(input$sepal_length %% 7)), 
colour="#BB0000", linetype="dashed", size=2)
    g

  })

})

当我执行程序时出现错误:Error: object 'input' not found

当我给出一个特定值 (not input$sepal_length) 时,例如 5,它会按应有的方式绘制,当我注释掉截距线时,它会呈现该图,没有预期的红线。当我将 renderPlot 更改为 renderText 并打印 input$sepal_length 的值时,它会打印输入的值。你能指导我哪里出错了吗?

您使用映射 (aes) 将变量插入到 `geom_vline?变化:

g <- g+geom_vline(aes(xintercept= as.numeric(input$sepal_length %% 7)), 
colour="#BB0000", linetype="dashed", size=2)

收件人:

g <- g+geom_vline(xintercept= as.numeric(input$sepal_length %% 7), 
colour="#BB0000", linetype="dashed", size=2)

它应该可以工作。