2013-11-21 1 views
10

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

enter image description here

Я хотел бы добавить еще один список ввода, так что можно выбрать, какой вар должен быть построен. При попытке запустить скрипт, кажется, запускается без каких-либо ошибок, но никакой сюжет не отображается, просто выберите меню. enter image description here

Возможно, есть ошибка при передаче переменных на server.R, поэтому выходные слоты не строятся правильно, просто догадка. Пробовал работать в общий способ создания функции в зависимости от ввода вары, но я что-то не хватает, может быть, о реакционной способности, может быть, правильно передает ВАР, ...

Эти коды ui.R

library("shiny") 
shinyUI(pageWithSidebar(

    headerPanel('Comparación de zonas - Temperatura'), 

    sidebarPanel(
    selectInput("panel1", "Zona:", 
          list("Zona 1" = "1", 
           "Zona 2" = "2", 
           "Zona 3" = "3", 
           "Zona 4" = "4")), 
    selectInput("panel2", "Zona:", 
       list("Zona 1" = "1", 
        "Zona 2" = "2", 
        "Zona 3" = "3", 
        "Zona 4" = "4")), 
    selectInput("var", "Variable:", 
       list("tempc" = "tempc", 
        "relhum" = "relhum")),  
    helpText('Al seleccionar la zona se crearán automáticamente 
    el gráfico de evolución temporal.') 
), 

    mainPanel(
    conditionalPanel(condition = "inputId == 'panel1'",plotOutput('myplot') 
    ), 
    conditionalPanel(condition = "inputId == 'panel2'",plotOutput("myplot") 
    )  
) 
)) 

и server.R

library(shiny) 
library(plyr) 
library(ggplot2) 

shinyServer(function(input, output) { 

    formulaText <- reactive(function() { 
    paste("Gràfica de ggplot: Zona ", input$zona1) 
    }) 

    # Return the formula text for printing as a caption 
    output$caption <- reactiveText(function() { 
    formulaText() 
    }) 

    # datasets 
    datos=read.table("data.dat",header=T) 
    data=as.data.frame(datos) 
    data=within(data, datetime <- as.POSIXct(paste(date, time),format = "%Y%m%d %H%M%S")) 

    rams <- reactive({ 
    subset(data,data$stat_id %in% places$stat_id[places$Zona == input$panel1])  
    }) 


    plot <- function(var) { 
    p <- ggplot(rams(),aes(x=datetime, y=var, colour=as.character(stat_id))) + 
     geom_line() 
    } 

    plot=p(input$var) 

    if(input$var == "tempc") { 
    plot <- plot + ylab("Temperatura (ºC)") + xlab(" ") + 
     ggtitle(gtitol) + theme(legend.title=element_blank()) + theme(legend.position="bottom") + 
     scale_y_continuous(limits = c(-20,ylim),breaks=c(seq(-20,ylim,by=2))) } 

    if (input$var == "relhum") { 
    plot <- plot + 
     ylab("Humedad relativa (%)") + xlab(" ") + 
     ggtitle(gtitol) + theme(legend.title=element_blank()) + theme(legend.position="bottom") + 
     scale_y_continuous(limits = c(0,100),breaks=c(seq(0,100,by=5))) } 

    output$myplot <- reactivePlot(function() { 
    print(plot) 
    }) 

}) 

заранее спасибо за помощь и советы

+0

'участок = р (вход $ var) 'is wrong –

+0

Да, но это была не единственная проблема. См. Мой ответ ниже. Благодарю. – pacomet

+0

Полезно знать 'aes_string()', чем вы для отправки этого ответа. –

ответ

10

Наконец я преуспел. Проблемы заключались в том, как переменные передаются из ввода ui.R на сервер.R и как ggplot имеет дело с таким вводом. Мне нужно было использовать aes_string для управления именами переменных. Теперь два первых списка выбора позволяют выбрать кадр данных, используемый в верхних/нижних графиках, в то время как третий выбирает переменную, которая должна быть построена, посредством создания различных команд ggplot.

Хотя скрипт работает прямо сейчас, есть еще некоторые проблемы для оптимизации кода, чтобы он мог работать более общим способом. Я создаю два разных кадра данных, подмножая их больше, и, возможно, лучше иметь только один и подмножество. Я определил два вывода вывода (myplot1 и myplot2), поскольку я не мог найти, как управлять только одним для двух условных панелей. Есть еще работа, но, как новичок в блестящей, я счастлив, что она работает.

В любом случае я прилагаю код работает для меня, и ожидаем, что это поможет кому-то:

ui.R

library("shiny") 
shinyUI(pageWithSidebar(

    headerPanel('Comparación de zonas - Temperatura'), 

    sidebarPanel(
    selectInput("panel1", "Zona:", 
          list("Zona 1" = "1", 
           "Zona 2" = "2", 
           "Zona 3" = "3")), 
    selectInput("panel2", "Zona:", 
       list("Zona 1" = "1", 
        "Zona 2" = "2", 
        "Zona 3" = "3")), 
    selectInput("var", "Variable:", 
       list("tempc" = "tempc", 
        "relhum" = "relhum")),  
    helpText('Al seleccionar la zona se crearán automáticamente 
    el gráfico de evolución temporal.') 
), 

    mainPanel(
    conditionalPanel(condition = "inputId == 'panel1'",plotOutput(outputId='myplot1')), 
    conditionalPanel(condition = "inputId == 'panel2'",plotOutput(outputId='myplot2')) 
) 
)) 

server.R

library(shiny) 
library(plyr) 
library(ggplot2) 

shinyServer(function(input, output) { 

    datos=read.table("data.dat",header=T) 
    pobles=read.table("pobles-zona.dat",header=T) 

    data=as.data.frame(datos) 
    places=as.data.frame(pobles) 

    data$time[data$time == "0"] = "000000" 
    data$time[data$time == "10000"] = "010000" 
    data$time[data$time == "20000"] = "020000" 
    data$time[data$time == "30000"] = "030000" 
    data$time[data$time == "40000"] = "040000" 
    data$time[data$time == "50000"] = "050000" 
    data$time[data$time == "60000"] = "060000" 
    data$time[data$time == "70000"] = "070000" 
    data$time[data$time == "80000"] = "080000" 
    data$time[data$time == "90000"] = "090000" 

    data=within(data, datetime <- as.POSIXct(paste(date, time),format = "%Y%m%d %H%M%S")) 

    formulaText <- reactive(function() { 
    paste("Gràfica de ggplot: Zona ", input$panel1, input$panel2, input$var) 
    }) 

    # Return the formula text for printing as a caption 
    output$caption <- reactiveText(function() { 
    formulaText() 
    }) 

    rams1 <- reactive({ 
    subset(data,data$stat_id %in% places$stat_id[places$Zona == input$panel1])  
    }) 
    rams2 <- reactive({ 
    subset(data,data$stat_id %in% places$stat_id[places$Zona == input$panel2])  
    }) 

    p <- function(data){ 
    p=ggplot(data(),aes_string(x="datetime", y=input$var,colour="as.character(stat_id)")) + 
    geom_line() 
    } 

    output$myplot1 <- reactivePlot(function() { 

    gtitol=paste("Zona ",input$panel1) 
    yx=round(max(rams1()$tempc)+2) 
    yn=round(min(rams1()$tempc)-2) 

    plot=p(rams1) 

    if (input$var == "tempc") { 
     plot=plot + ylab("Temperatura (ºC)") + xlab(" ") + 
     ggtitle(gtitol) + theme(legend.title=element_blank()) + theme(legend.position="bottom") + 
     scale_y_continuous(limits = c(yn,yx),breaks=c(seq(yn,yx,by=2))) 
    } 

    if (input$var == "relhum" ){ 
     plot=plot + ylab("Humedad relativa (%)") + xlab(" ") + 
     ggtitle(gtitol) + theme(legend.title=element_blank()) + theme(legend.position="bottom") + 
     scale_y_continuous(limits = c(0,100),breaks=c(seq(0,100,by=5))) 
    } 
    print(plot) 
    }) 

    output$myplot2 <- reactivePlot(function() { 

     gtitol=paste("Zona ",input$panel2) 
     yx=round(max(rams2()$tempc)+2) 
     yn=round(min(rams2()$tempc)-2)  

     plot=p(rams2) 

     if (input$var == "tempc") { 
     ylim=max(rams2()$tempc)+2 
     plot=plot + ylab("Temperatura (ºC)") + xlab(" ") + 
     ggtitle(gtitol) + theme(legend.title=element_blank()) + theme(legend.position="bottom") + 
     scale_y_continuous(limits = c(yn,yx),breaks=c(seq(yn,yx,by=2))) 
     } 
     if (input$var == "relhum" ) { 
     ylim=100 
     plot=plot + ylab("Humedad relativa (%)") + xlab(" ") + 
     ggtitle(gtitol) + theme(legend.title=element_blank()) + theme(legend.position="bottom") + 
     scale_y_continuous(limits = c(0,100),breaks=c(seq(0,100,by=5))) 
     } 
    print(plot) 
    }) 
})