ggplots не отображаются в Shiny - PullRequest
0 голосов
/ 25 февраля 2019

Прямо сейчас я пытаюсь создать приложение блестящие из набора данных о потреблении алкоголя от Всемирной организации здравоохранения.Я построил карты на основе этих данных и заставил эти результаты работать, но сейчас я пытаюсь отобразить первую десятку стран с точки зрения потребляемых напитков, и два из этих графиков не отображаются (для пива и вина).

Вы можете понять, что я имею в виду, посмотрев на мое блестящее приложение здесь:

https://mdsil11.shinyapps.io/worldMap/

Странно то, что мой код работает, когда я использую более простые графики вместо ggplotonesкак история (rnorm (100)).Еще одна странная вещь заключается в том, что эти графики работают, когда я запускаю их в обычном R-скрипте.Наконец, мой последний сюжет (сюжет для спиртных напитков или смешанных напитков) показывает, но не для вина или пива.

Вот код:

library(shiny)
[library(rworldmap)
library(ggplot2)
library(tidyverse)


## defining datasets
wineDrinks = drinks\[ , c(2,5)\]
spiritDrinks = drinks\[ , c(2,4)\]
beerDrinks = drinks\[ , c(2,3)\]

topWine <- wineDrinks %>% arrange(desc(wine_servings))
topBeer <- beerDrinks %>% arrange(desc(beer_servings))
topSpirits <- spiritDrinks %>% arrange(desc(spirit_servings))

top10beer <- topBeer[0:10, ]
top10wine <- topWine[0:10, ]
top10spirits <- topSpirits[0:10, ]

## defining map objects
w <- joinCountryData2Map(drinksISO, joinCode = 'ISO3', nameJoinColumn = 'ISO', verbose = TRUE)
s <- joinCountryData2Map(drinksISO, joinCode = 'ISO3', nameJoinColumn = 'ISO', verbose = TRUE)
b <- joinCountryData2Map(drinksISO, joinCode = 'ISO3', nameJoinColumn = 'ISO', verbose = TRUE)

##### Shiny Application #####

ui <- fluidPage(
  titlePanel('Global Alcohol Consumption'),
  #each input should have a unique input ID
  sidebarPanel(
  radioButtons(inputId = 'Alc', label = 'Alcohol Type',
              choices = list('Beer','Wine','Spirits'))
  )
  , mainPanel(
    plotOutput('map'), plotOutput('TopTen')
    )
)


server <- function(input, output) {
  output$map <- renderPlot({
    if(input$Alc == 'Beer'){
      mapCountryData(mapToPlot = b,nameColumnToPlot = 'beer_servings', mapTitle = 'World Beer Consumption',  missingCountryCol = "grey", oceanCol = "lightblue1")
    }

    if(input$Alc == 'Wine'){
      mapCountryData(mapToPlot = w,nameColumnToPlot = 'wine_servings', mapTitle = 'World Wine Consumption',  missingCountryCol = "grey", oceanCol = "lightblue1")
    }

    if(input$Alc == 'Spirits'){
      mapCountryData(mapToPlot = s, nameColumnToPlot = 'spirit_servings', mapTitle = 'World Spirits Consumption',  missingCountryCol = "grey", oceanCol = "lightblue1")
    }

  })


  output$TopTen <- renderPlot({

     #### PROBLEM LIES HERE #####

    if(input$Alc == 'Beer'){
      ggplot(top10beer,aes(x = reorder(country, -beer_servings), y = beer_servings)) + geom_point(size = 3) + geom_segment(aes(x = country, xend = country, y = 0, yend = beer_servings)) + labs(title="Lollipop Chart", subtitle = 'Top 10 beer drinking countries') + theme(axis.text.x = element_text(angle=65, vjust=0.6)) + xlab('Countries')
    }
    if(input$Alc == 'Wine'){
      ggplot(top10wine, aes(x = reorder(country, -wine_servings), y = wine_servings)) + geom_point(size = 3) + geom_segment(aes(x = country, xend = country, y = 0, yend = wine_servings)) + labs(title="Lollipop Chart", subtitle = 'Top 10 wine drinking countries') + theme(axis.text.x = element_text(angle=65, vjust=0.6)) + xlab('Countries')
    }

   #### BUT THIS WORKS ####

    if(input$Alc == 'Spirits'){
      ggplot(top10spirits,aes(x = reorder(country, -spirit_servings), y = spirit_servings)) + geom_point(size = 3) + geom_segment(aes(x = country, xend = country, y = 0, yend = spirit_servings)) + labs(title="Lollipop Chart", subtitle = 'Top 10 spirit drinking countries') + theme(axis.text.x = element_text(angle=65, vjust=0.6)) + xlab('Countries')
    }
  }
  )

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

Буду очень признателен за любую помощь / указатели по получению двух других графиков для показа!

1 Ответ

0 голосов
/ 25 февраля 2019

Измените эти отдельные if операторы на if/else/else.Ваш кодовый блок renderPlot должен возвращать объект ggplot.Если последняя строка вашего блока - if, и это оценивается как ЛОЖЬ, из блока ничего не возвращается.Значения из предыдущих операторов if в основном игнорируются.Вызов ggplot() на самом деле не рисует график так же, как это делают базовые графические функции, как hist.На самом деле вам нужно напечатать значение, возвращаемое ggplot, чтобы вызвать построение графика.

Вот один из способов переписать ваш блок.

output$TopTen <- renderPlot({

    if(input$Alc == 'Beer'){
      ggplot(top10beer,aes(x = reorder(country, -beer_servings), y = beer_servings)) + geom_point(size = 3) + geom_segment(aes(x = country, xend = country, y = 0, yend = beer_servings)) + labs(title="Lollipop Chart", subtitle = 'Top 10 beer drinking countries') + theme(axis.text.x = element_text(angle=65, vjust=0.6)) + xlab('Countries')
    } else if(input$Alc == 'Wine'){
      ggplot(top10wine, aes(x = reorder(country, -wine_servings), y = wine_servings)) + geom_point(size = 3) + geom_segment(aes(x = country, xend = country, y = 0, yend = wine_servings)) + labs(title="Lollipop Chart", subtitle = 'Top 10 wine drinking countries') + theme(axis.text.x = element_text(angle=65, vjust=0.6)) + xlab('Countries')
    } else if (input$Alc == 'Spirits'){
      ggplot(top10spirits,aes(x = reorder(country, -spirit_servings), y = spirit_servings)) + geom_point(size = 3) + geom_segment(aes(x = country, xend = country, y = 0, yend = spirit_servings)) + labs(title="Lollipop Chart", subtitle = 'Top 10 spirit drinking countries') + theme(axis.text.x = element_text(angle=65, vjust=0.6)) + xlab('Countries')
    } else {
        stop("unknown plot type")
    }
})
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...