R:使用闪亮创建一个应用程序来绘制一个 csv 文件

问题描述

我正在尝试在 R 中创建一个闪亮的应用程序,该应用程序使用我拥有的 CSV 文件,但是在尝试发布它时我一直收到错误消息。 这是我的代码: `

library(shiny)
library(plotly)
library(dplyr)
library(ggplot2)
library(DT)

# Define UI for application that draws a histogram
ui <- fluidPage(# Application title
    titlePanel("Hello"),# Show a plot of the generated distribution
    mainPanel(fig))


server <- function(input,output) {
    output$table <- renderDT(investors)
    output$fig <- renderPlot({
        #
        count_distinct_investors = investors %>% group_by(Marital_Status) %>% summarize(count =
                                                                                            n())
        
        p = ggplot(count_distinct_investors,aes(
                       x = reorder(Marital_Status,-count),y = count,fill = Marital_Status
                   )) + geom_bar(stat = "identity") +
            coord_flip() + labs(title = "investors Count") + labs(x = "Marital_Status")
        
        fig = ggplotly(p)
        fig
        
        
        
    })
}

# Run the application
shinyApp(ui = ui,server = server)

`

我已经预先加载到称为投资者的环境中并有一个名为 Marital_Status 的列。 这是我在尝试发布应用程序时遇到的错误:`应用程序无法启动:

exited unexpectedly with code 1

Loading required package: ggplot2

Attaching package: ‘plotly’

The following object is masked from ‘package:ggplot2’:

    last_plot

The following object is masked from ‘package:stats’:

    filter

The following object is masked from ‘package:graphics’:

    layout


Attaching package: ‘dplyr’

The following objects are masked from ‘package:stats’:

    filter,lag

The following objects are masked from ‘package:base’:

    intersect,setdiff,setequal,union


Attaching package: ‘DT’

The following objects are masked from ‘package:shiny’:

    dataTableOutput,renderDataTable

Error in value[[3L]](cond) : object 'fig' not found
Calls: local ... tryCatch -> tryCatchList -> tryCatchOne -> <Anonymous>
Execution halted`

解决方法

如果你想 plotly 成为你的输出,你需要记住以下几点:

  1. 在服务器中:output$fig <- renderPlotly 而不是 output$fig <- renderPlot
  2. 在用户界面中:mainPanel(plotlyOutput("fig")) 而不是 mainPanel(fig))
  3. 您不必将情节分配给一个对象,只需在最后留下 ggplotly(p)

你可以试试这个代码看看它是如何工作的:

library(shiny)
library(ggplot2)
library(ggthemes)
library(plotly)

ui <- fluidPage(  
  titlePanel("Plotly"),sidebarLayout(
    sidebarPanel(),mainPanel(
      plotlyOutput("plot2"))
    ))

server <- function(input,output) {
  
  output$plot2 <- renderPlotly({
    ggplotly(
      ggplot(data = mtcars,aes(x = disp,y = cyl)) + 
        geom_smooth(method = lm,formula = y~x) + 
        geom_point() + 
        theme_gdocs())
  })
}

shinyApp(ui,server)