R从选择列表到反应性绘图闪亮传递变量 [英] R shiny pass variables from select list to reactive plot

查看:325
本文介绍了R从选择列表到反应性绘图闪亮传递变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用闪亮的包装进行第一次尝试,这很棒。但是,像往常一样,我面临一些问题。我已经管理,遵循闪亮的教程和谷歌,显示两个不同的气象站的图表,但都显示相同的变量。

/i.stack.imgur.com/FJT8t.pngalt =在这里输入图片描述>

我想添加另一个输入列表,因此可以选择哪个var将被绘制。当试图运行脚本时,它似乎运行时没有任何错误,但没有出现剧情,只是选择了菜单。

也许在将变量传递给server.R时存在一个错误,因此输出重叠图不能正确构建,只是猜测。试图以通用的方式创建取决于输入变量的函数,但我错过了某些东西,可能是关于反应性,也许正确地传递了变量,...



这些代码对于ui.R

  library(shiny)
shinyUI(pageWithSidebar(

headerPanel('Comparaciónde 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,
$select(var,Variable:,
list(tempc=tempc,
relhum= $ 4) relhum)),
帮助Text('Al seleccionar la zona secrearánautomáticamente
elgráficodeevolucióntemporal。')
),

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àficade ggplot:Zona,input $ zona1)
})

#返回打印的公式文本作为标题
输出$ caption< - reactiveText(function(){
formulaText()
))

#数据集
datos = read.table(data.dat,header = T)
data = as.data.frame(datos)
data = within(data,datetime< - as.POSixct (粘贴(日期,时间),格式=%Y %(%m%d%H%M%S))

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


plot < - function(var){
p < - ggplot(rams(),aes(x = datetime,y = var,color = 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 =)})}

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

输出$ myplot< - reactivePlot(函数n(){
print(plot)
})

})

预先感谢您的帮助和建议 最后我成功了。问题出在两个变量从ui.R输入传递给server.R以及ggplot如何处理这样的输入。我不得不使用aes_string来管理变量名称。现在,通过创建不同的ggplot命令,两个第一个选择列表允许选择上/下图中使用的数据帧,而第三个选择列表选择要绘制的变量。



尽管脚本现在正在工作,但仍然存在一些优化代码的问题,所以它可以以更一般的方式工作。我通过对更大的子集进行子集化来构造两个不同的数据帧,也许最好只有一个子集。我已经定义了两个绘图输出(myplot1和myplot2),因为我找不到如何管理两个条件面板中的一个。还有工作,但作为一个新手闪亮我很高兴它正在运行。

在任何情况下,我附上代码为我工作,并期望它会帮助某人:

ui.R

  library(shiny)
shinyUI(pageWithSidebar(
$ b headerPanel('Comparacion de zonas - Temperatura'),

sidebarPanel(
selectInput(panel1,Zona:,
list(Zona 1=1,
Zona 2=2,
Zona 3=3)),
selectInput( (Zona 1=1,
Zona 2=2,
Zona 3=3)) ,
selectInput(var,Variable:,
list(tempc=tempc,
relhum=relhum)),
helpText 'Al seleccionar la zona secrearánautomáticamente
elgráficodeevolucióntemporal。')
),
$ b mainPanel(
conditionalPanel(condition =inputId =='panel1',plotOutput(outputId ='myplot1')),
conditionalPanel(condition =inputId = ='panel2',plotOutput(outputId ='myplot2'))

))

server.R

 库(闪亮)
库(plyr)
库( ggplot2)
$ b $ shinyServer(函数(输入,输出){

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] =07000 0
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àficade ggplot:Zona,input $ panel1,input $ panel2,input $ var)
})

#返回打印的公式文本作为标题
输出$ caption< - reactiveText(function(){
formulaText()
))

rams1< - ({
子集(数据,数据$ stat_id%in%places $ stat_id [places $ Zona == input $ panel1])$ ​​b $ b})
rams2 < - reactive({
子集(数据,数据$ stat_id%in%places $ stat_id [places $ Zona == input $ panel2])
})

p < - 函数(数据){
p = ggplot(data(),aes_string(x =datetime,y = input $ var,color =as.character(stat_id)))+
geom_line()
}

output $ myplot1< - reactivePlot(function(){

gtitol = paste(Zona,输入$ 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 =(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)
} )

输出$ myplot2< - reactivePlot(function(){
$ b $ gt gt = paste(Zona,输入$ 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情节)
})
})


I am making my first attempts with shiny package, it's awesome. But, as usual, I am facing some problems. I've managed, following shiny tutorial and googleing, to show two different plots of different meteo stations but both showing the same variable.

I wanted to add another input list so it is possible to choose which var is to be plotted. When trying to run the script it seems to run without any errors but no plot appear, just the select menues.

Maybe there is a mistake in passing the variables to server.R so the output oblject plots are not properly build, just a guess. Tried to work in a general way creating functions depending on input vars but I am missing something, maybe about reactivity, maybe correctly passing vars,...

These are the codes for 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")
    )    
  )  
))

and 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)
  })  

})

Thank you in advance for your help and advice

解决方案

Finally I've succeeded. The problems were in both the way variables are passed from ui.R input to server.R and how ggplot deals with such input. I've had to use aes_string to manage variable names. Now, the two first select list permits to select the data frame used in the upper/bottom plots while the third selects the variable to be plotted, by means of creating different ggplot commands.

Although the script is working right now there are still some issues to optimize the code so it can work in a more general way. I construct two different data frames by subsetting the bigger one and maybe is better to have only one and subset. I have defined two plot outputs (myplot1 and myplot2) as I could not find how to manage only one for the two conditional panels. There is still work but as a newbie in shiny I'm happy it is running.

In any case I attach the code working for me and expect it will help someone:

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)
  })
})

这篇关于R从选择列表到反应性绘图闪亮传递变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆