簡體   English   中英

在R中使用已保存的ggplot2圖並使其具有光澤

[英]Using saved ggplot2 figure with shiny in r

我想繪制一個密度圖,將其保存並在閃亮的應用程序中進行渲染。 我想動態添加到圖中的是從輸入開始的一行,顯示新輸入的變量在密度圖中的位置:我將虹膜數據中的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中的暗線。 現在,在shinyui.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

當我給出一個像5這樣的特定值( not input$sepal_length )時,它會按照需要繪制,當我注釋掉攔截線時,它將繪制該圖,而沒有出現紅線。 當我將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)

它應該工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM