Ответ 1
Наконец, я преуспел. Проблемы заключались в том, как переменные передаются из ввода ui.R на сервер .R и как ggplot имеет дело с таким вводом. Мне нужно было использовать aes_string для управления именами переменных. Теперь два первых списка выбора позволяют выбрать кадр данных, используемый в верхних/нижних графиках, в то время как третий выбирает переменную, которая должна быть построена, посредством создания различных команд ggplot.
Хотя script работает прямо сейчас, есть еще некоторые проблемы для оптимизации кода, чтобы он мог работать более общим образом. Я создаю два разных кадра данных, подмножая их больше, и, возможно, лучше иметь только один и подмножество. Я определил два вывода вывода (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)
})
})