Блестящий, не показывающий мой ggplot, как я ожидал - программирование
Подтвердить что ты не робот

Блестящий, не показывающий мой ggplot, как я ожидал

Что удерживает мое маленькое Блестящее приложение от отображения моего ggplot? Когда я заменяю код в renderPlot() примером, использующим функцию базового графика, он объединяется. Я использую RStudio, R v3.0.1 в Windows Vista, выводя в браузер Chrome.

ui.r

library(ggplot2)

cities <- c("Anchorage","Fairbanks","Juenau","Wasilla","Homer")
years <- 2003:2013
Table <- "Capital Assets"
Account <- c("Land", "Art", "Buildings", "Equipment")
dat <- data.frame(City = sort(rep(cities, length(years))), Year = rep(years,length(cities)), Table)
sampleDat <- rbind(data.frame(dat,Acount = Account[1]), data.frame(dat, Acount = Account[2]), data.frame(dat, Acount = Account[3]), data.frame(dat, Acount = Account[4]))
finalDat <- data.frame(sampleDat, Value = runif(length(sampleDat[,1]), 1000,10000) )

shinyUI(pageWithSidebar(

  headerPanel("CAFR Explorer"),

  selectInput("city","City", as.list(levels(finalDat$City)), selected = NULL, multiple = FALSE),

  mainPanel(
    h3(textOutput("caption")),

    plotOutput("CAFRplot")
)))   

server.r

library(shiny)
library(ggplot2)

cities <- c("Anchorage","Fairbanks","Juenau","Wasilla","Homer")
years <- 2003:2013
Table <- "Capital Assets"
Account <- c("Land", "Art", "Buildings", "Equipment")
dat <- data.frame(City = sort(rep(cities, length(years))), Year = rep(years,length(cities)), Table)
sampleDat <- rbind(data.frame(dat,Acount = Account[1]), data.frame(dat, Acount = Account[2]), data.frame(dat, Acount = Account[3]), data.frame(dat, Acount = Account[4]))
finalDat <- data.frame(sampleDat, Value = runif(length(sampleDat[,1]), 1000,10000) )

shinyServer(function(input, output) {

  formulaText <- reactive({
    paste(input$city)
  })

  output$caption <- renderText({
    formulaText()
  })

  output$CAFRplot <- renderPlot({

    ## this one isn't working.
    ggplot(finalDat, aes(x = finalDat[which(finalDat$City == input$city),2], 
                         y = finalDat[which(finalDat$City == input$city),5])) +
    geom_point()

    ## this one is working
    #plot(finalDat[which(finalDat$City == input$city),2], y = finalDat[which(finalDat$City == input$city),5])


  })
})
4b9b3361

Ответ 1

Здесь есть две проблемы.

Во-первых, вы не должны подмножаться в aes - он ожидает имена столбцов. Вместо этого подмножество data.frame, которое вы предоставляете ggplot (благодаря @Roland из чата R)

Во-вторых, вы должны явно print ваш объект ggplot в своем блестящем приложении.

Попробуйте следующее:

p <- ggplot(finalDat[finalDat$City == input$city,], aes(x = Year, y = Value))
p <- p + geom_point()
print(p)

Ответ 2

Для вашего кода понадобилось пару изменений, чтобы получить рендеринг ggplot. Как указано выше, требуется print(ggplot). Но также, внутри внутри ggplot не может справиться с подмножеством.

Итак, вы подсетете свой интерес к отдельному реагированию и назовите это из ggplot.

city.df <- reactive({
    subset(finalDat, City == input$city)
  })  

  output$CAFRplot <- renderPlot({
    city <- city.df()

    print(ggplot(city, aes(x = Year, y=Value)) + geom_point())

Полный сервер .R(это работает)

library(shiny)
library(ggplot2)

cities <- c("Anchorage","Fairbanks","Juenau","Wasilla","Homer")
years <- 2003:2013
Table <- "Capital Assets"
Account <- c("Land", "Art", "Buildings", "Equipment")
dat <- data.frame(City = sort(rep(cities, length(years))), Year = rep(years,length(cities)), Table)
sampleDat <- rbind(data.frame(dat,Acount = Account[1]), data.frame(dat, Acount = Account[2]), data.frame(dat, Acount = Account[3]), data.frame(dat, Acount = Account[4]))
finalDat <- data.frame(sampleDat, Value = runif(length(sampleDat[,1]), 1000,10000) )

shinyServer(function(input, output) {

  formulaText <- reactive({
    paste(input$city)
  })

  output$caption <- renderText({
    formulaText()
  })

  city.df <- reactive({
    subset(finalDat, City == input$city)
  })  

  output$CAFRplot <- renderPlot({
    city <- city.df()
    ## this one isn't working.
#    print(ggplot(finalDat, aes(x = finalDat[which(finalDat$City == input$city),2], 
#                         y = finalDat[which(finalDat$City == input$city),5])) +  geom_point())

    print(ggplot(city, aes(x = Year, y=Value)) + geom_point())

    ## this one is working
    #plot(finalDat[which(finalDat$City == input$city),2], y = finalDat[which(finalDat$City == input$city),5])


  })
})

Ответ 3

В ggplot2 вы можете подмножить общие данные, передаваемые на все уровни (ответ @GSee), или для отдельных уровней вы можете использовать аргумент subset для подмножества только для этого слоя. Это может быть полезно, если вы строите более сложные графики.

Использование функции plyr . полезно здесь для построения аргументов

# required in server.R (along with the other calls to library)
library(plyr)

 p <- ggplot(finalDat, aes(y =Year, x = Value)) + 
        geom_point(subset = .(City ==input$city))
 print(p)