Блестящий - не удается отобразить штриховой график

Почему не отображается гистограмма? Если я запускаю тот же код вне более крупной программы, отображается штриховая диаграмма. Я получаю переключатели и схему диаграмм, но никаких данных внутри нет. Я включил сервер, пользовательский интерфейс и данные ниже. Я новичок в сиянии.

Я пробовал использовать скобки, запятые и круглые скобки в нескольких местах. Я не нашел решения.

UI.r
#UI Program
library(shiny)
library(shinydashboard)
library(ggplot2)
library(ggthemes)
library(DT)

# my data
my_data=read.table("hack.csv", header=T, sep = ",")
# changing date to categorical data 
#my_data$Year=factor(my_data$Year)

## Preparing sidebar items
sidebar <- dashboardSidebar(
  width = 300,
  sidebarMenu(
    menuItem(h3("Dashboard"), tabName = "dashbd"),
    menuItem(h3("Data"), tabName = "datafile"),
    menuItem(h3("Visualization of Data"), tabName = "graphs", 
         menuSubItem(h4("- Barplot"), tabName = "crime")    ),

    br(),
    br(),
    hr()
  )
)
## Preparing for the body items
body <- dashboardBody(
  tabItems(
    tabItem(tabName = "dashbd",
        fluidRow(
          valueBoxOutput("vbox1", width = 6),
          valueBoxOutput("vbox2", width = 6)),
        h2("Introduction",  align = "center", style = "font-family: 'times'; color:blue"),
        h3("Cyber crime damage costs to hit $6 trillion annually by 2021. It all begins and ends with cyber crime. Without it, there's nothing to cyber-defend. The cybersecurity community and major media have largely concurred on the prediction that cyber crime damages will cost the world $6 trillion annually by 2021, up from $3 trillion in 2015. This represents the greatest transfer of economic wealth in history, risks the incentives for innovation and investment, and will be more profitable than the global trade of all major illegal drugs combined"),
        fluidPage(
          fluidRow(
            column(
              h2("About this app ...", align = "center", style = "font-family: 'times'; color:blue"),
              h3("This app helps you to explore and visualize the motivation behind cyber attacks
                 I have used the database available",  a("here.",href = "https://www.hackmageddon.com/about/"), 
                 style = "font-family: 'times'"),
              width = 4,
              align = "left"

            ),
            column(
              h2("How to use!", style = "font-family: 'times'; color:blue"),
              h3("This app contains multiple sections;  the database and several visual graphs. ", 
                 style = "font-family: 'times'"),              
              width = 8,
              align = "left"
            ),
            br(),
            br()
            )
        ),
        p()
    ),  
    tabItem(tabName = "datafile",
        box(title = "Motivation of Cyber Attacks in Italy",
            width = 12, 
            DT::dataTableOutput('da.tab'))  
    ),

#the select for barplot
tabItem(tabName = "crime",
        titlePanel(title = h4("Cyber Attacks in Italy by Year", align = "center")),
        sidebarPanel(

          radioButtons("YEAR", "Select the Census Year",
                       choices = c("2017", "2016", "2015","2014"),
                       selected = "2017")),


        sidebarPanel(
          plotOutput("MyBar"))
    )  

  )  )

# Show a plot of the generated distribution
## Putting them together into a dashboardPage

ui <- dashboardPage( 
  skin = "blue",
  # add this -> navbarMenu()
  dashboardHeader(
    title = "MOTIVATION BEHIND CYBER ATTACKS IN ITALY",
    titleWidth = 550,
    tags$li(class = "dropdown"
    )
  ),
  sidebar,
  body
)

SERVER
    # Reading data set
my_data=read.table("hack.csv", header=T, sep = ",")
#number of row of data
my_data$Year=as.factor(my_data$Year)
server <- function(input, output) {
  ## Information for dashboard tab 
  # Reading data set
  my_data=read.table("hack.csv", header=T, sep = ",")
  #number of row of data
  my_data$Year=as.factor(my_data$Year)

  server <- function(input, output) {



## Information for data tab
# data table output


output$da.tab <- DT::renderDataTable(datatable(my_data, extensions = 'Buttons',
                                               style = "bootstrap",
                                               filter = list(position = 'top', clear = T, plain = F),
                                               options = list(pageLength = 1500, dom = 'Bfrtip', 
                                                              buttons = 
                                                                list('copy', 'print', list(
                                                                  extend = 'collection',
                                                                  buttons = c('csv', 'excel', 'pdf'), 
                                                                  text = 'Download')
                                                                )
                                               )
    )    )


  }
  ## Information for data tab
  # data table output


  output$da.tab <- DT::renderDataTable(datatable(my_data, extensions = 'Buttons',
                                             style = "bootstrap",
                                             filter = list(position = 'top', clear = T, plain = F),
                                             options = list(pageLength = 1500, dom = 'Bfrtip', 
                                                            buttons = 
                                                              list('copy', 'print', list(
                                                                extend = 'collection',
                                                                buttons = c('csv', 'excel', 'pdf'), 
                                                                text = 'Download')
                                                              )
                                             )  )  )


  #This is used to create the BarPlot
  server <- function(input,output){

    reactive_data = reactive({
  #Reading from the datbase for year selected
  selected_year = as.numeric(input$YEAR)
  return(data[data$year==selected_year,])

    })
    #outputting the bar data
    output$bar <- renderPlot({
      color <- c("blue", "red", "yellow")

      our_data <- reactive_data()

      barplot(colSums(our_data[,c("CyberCrime","CyberWar","CyberHacks")]),
          ylab = "Total",
          xlab = "Census Year",
          names.arg = c("CyberCrime","CyberWar","CyberHacks"),
          col = color)
            })
      }}


DATA
#This is the data for the query
Year,CyberCrime,CyberWar,CyberHacks,CyberEspionage
2017,60,45,12,16
2016,65,40,16,14
2015,55,38,10,9
2014,50,26,9,6

Может быть непоследовательное именование? Разные идентификаторы в output$bar и plotOutput("MyBar")

Aurèle 01.05.2018 18:43

Это не так - я, вероятно, перепутал имена, пытаясь решить проблему разными способами. Когда у меня есть совпадение, гистограмма не отображается. Понятия не имею, почему бы и нет.

Jacey 01.05.2018 22:03
Стоит ли изучать PHP в 2023-2024 годах?
Стоит ли изучать PHP в 2023-2024 годах?
Привет всем, сегодня я хочу высказать свои соображения по поводу вопроса, который я уже много раз получал в своем сообществе: "Стоит ли изучать PHP в...
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Приемы CSS-макетирования - floats и Flexbox
Приемы CSS-макетирования - floats и Flexbox
Здравствуйте, друзья-студенты! Готовы совершенствовать свои навыки веб-дизайна? Сегодня в нашем путешествии мы рассмотрим приемы CSS-верстки - в...
Тестирование функциональных ngrx-эффектов в Angular 16 с помощью Jest
В системе управления состояниями ngrx, совместимой с Angular 16, появились функциональные эффекты. Это здорово и делает код определенно легче для...
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Пользовательский скаляр GraphQL
Пользовательский скаляр GraphQL
Листовые узлы системы типов GraphQL называются скалярами. Достигнув скалярного типа, невозможно спуститься дальше по иерархии типов. Скалярный тип...
1
2
1 055
2

Ответы 2

У вас действительно была проблема с именованием, как указал Аурел в комментариях, но, что более тревожно, у вас были определены вложенные функции server ... Я списываю это на плохую работу копирования-вставки, но вот рабочая версия. Я добавил shiny::validate, чтобы убедиться, что он не пытается построить гистограмму при отсутствии данных.

library(shiny)
library(shinydashboard)
library(ggplot2)
library(ggthemes)
library(DT)

my_data <- read.table(text = "
Year,CyberCrime,CyberWar,CyberHacks,CyberEspionage
2017,60,45,12,16
2016,65,40,16,14
2015,55,38,10,9
2014,50,26,9,6", sep = ",", header = TRUE)


## Preparing sidebar items
sidebar <- dashboardSidebar(
  width = 300,
  sidebarMenu(
    menuItem(h3("Dashboard"), tabName = "dashbd"),
    menuItem(h3("Data"), tabName = "datafile"),
    menuItem(h3("Visualization of Data"), tabName = "graphs", 
             menuSubItem(h4("- Barplot"), tabName = "crime")    ),

    br(),
    br(),
    hr()
  )
)
## Preparing for the body items
body <- dashboardBody(
  tabItems(
    tabItem(tabName = "dashbd",
            fluidRow(
              valueBoxOutput("vbox1", width = 6),
              valueBoxOutput("vbox2", width = 6)),
            h2("Introduction",  align = "center", style = "font-family: 'times'; color:blue"),
            h3("Cyber crime damage costs to hit $6 trillion annually by 2021. It all begins and ends with cyber crime. Without it, there's nothing to cyber-defend. The cybersecurity community and major media have largely concurred on the prediction that cyber crime damages will cost the world $6 trillion annually by 2021, up from $3 trillion in 2015. This represents the greatest transfer of economic wealth in history, risks the incentives for innovation and investment, and will be more profitable than the global trade of all major illegal drugs combined"),
            fluidPage(
              fluidRow(
                column(
                  h2("About this app ...", align = "center", style = "font-family: 'times'; color:blue"),
                  h3("This app helps you to explore and visualize the motivation behind cyber attacks
                     I have used the database available",  a("here.",href = "https://www.hackmageddon.com/about/"), 
                     style = "font-family: 'times'"),
                  width = 4,
                  align = "left"

                ),
                column(
                  h2("How to use!", style = "font-family: 'times'; color:blue"),
                  h3("This app contains multiple sections;  the database and several visual graphs. ", 
                     style = "font-family: 'times'"),              
                  width = 8,
                  align = "left"
                ),
                br(),
                br()
                )
            ),
            p()
    ),  
    tabItem(tabName = "datafile",
            box(title = "Motivation of Cyber Attacks in Italy",
                width = 12, 
                DT::dataTableOutput('da.tab'))  
    ),

    #the select for barplot
    tabItem(tabName = "crime",
            titlePanel(title = h4("Cyber Attacks in Italy by Year", align = "center")),
            sidebarPanel(

              radioButtons("YEAR", "Select the Census Year",
                           choices = c("2017", "2016", "2015","2014"),
                           selected = "2017")),


            sidebarPanel(
              plotOutput("MyBar"))
    )  

  )  )

# Show a plot of the generated distribution
## Putting them together into a dashboardPage

ui <- dashboardPage( 
  skin = "blue",
  # add this -> navbarMenu()
  dashboardHeader(
    title = "MOTIVATION BEHIND CYBER ATTACKS IN ITALY",
    titleWidth = 550,
    tags$li(class = "dropdown"
    )
  ),
  sidebar,
  body
)


server <- function(input, output) {

  output$da.tab <- DT::renderDataTable(
    datatable(
      data = my_data, 
      extensions = 'Buttons',
      style = "bootstrap",
      filter = list(position = 'top', clear = T, plain = F),
      options = list(
        pageLength = 1500,
        dom = 'Bfrtip', 
        buttons = list(
          'copy', 
          'print',
          list(
            extend = 'collection',
            buttons = c('csv', 'excel', 'pdf'), 
            text = 'Download')
          ) #/ buttonList
        ) #/ options 
      ) #/ datatable
    ) #/ renderDataTable

  reactive_data = reactive({
    #Reading from the datbase for year selected
    my_data[my_data$Year == input$YEAR,]

  })

  #outputting the bar data
  output$MyBar <- renderPlot({
    color <- c("blue", "red", "yellow")

    our_data <- reactive_data()

    shiny::validate(
      need(nrow(our_data) > 0, "No data for that year!")
    )

    barplot(colSums(our_data[,c("CyberCrime","CyberWar","CyberHacks")]),
            ylab = "Total",
            xlab = "Census Year",
            names.arg = c("CyberCrime","CyberWar","CyberHacks"),
            col = color)
  })

}

shinyApp(ui, server)

Спасибо вам обоим - без вас я бы не справился! @

Jacey 02.05.2018 14:11

@Jacey - если это решило вашу проблему, обязательно примите этот ответ (нажмите на галочку), чтобы показать другим пользователям, что это решило вашу проблему.

phalteman 02.05.2018 20:15

Ответ @mlegge хороший (и должен быть принятым ответом) - основной проблемой были вложенные функции сервера. Но вы можете еще больше упростить работу сервера. Поскольку renderPlot является реактивной средой, вы можете подмножество данных внутри вашего вызова renderPlot следующим образом:

output$MyBar <- renderPlot({
  our_data <- my_data[my_data$Year==input$YEAR,]
  color <- c("blue", "red", "yellow")

  barplot(colSums(our_data[,c("CyberCrime","CyberWar","CyberHacks")]),
          ylab = "Total",
          xlab = "Census Year",
          names.arg = c("CyberCrime","CyberWar","CyberHacks"),
          col = color)
})

Это исключает ненужное присвоение reactive_data.

Другие вопросы по теме