R-ggplot2 in Shiny - 如何从之前的图/图中提取/获取/设置当前x / y /两个轴范围?

时间:2014-03-30 05:45:33

标签: r ggplot2 shiny

我正在使用Shiny包。 我有一个ggplot2图表,只要用户更改输入,它的边界就会自动更新。我有一个控件,上面写着“修正当前轴范围”。

我希望控件确定先前Shiny图的当前x和/或y范围,并将其用作即将创建的新图的输入。

我打算使用像coord_cartesian这样的函数来修复所需的边界。

另一个选择是简单地使用一个函数,可以选择固定x,y或两个边界,但我找不到运气。

如何做到这一点?

-------------的更新 ---------------

尝试使用全局变量失败,因为coord_cartesian没有返回我的预期。它返回什么(我找不到文档)?

#---------------SNIPPET---------------
#global variable
yaxis

#renderPlot 
if(input$yaxis == "default") {
    y <- coord_cartesian(ylim = c(-1, 1))
    yaxis <- y
}
else if(input$yaxis == "variable") {

    yaxis <- ggplot_build(q)$panel$ranges[[1]]$y.range
}
else if(input$yaxis == "fixed") {
    y <- yaxis
}

print(q + y)

2 个答案:

答案 0 :(得分:1)

如果您不介意当前比例是全局的,即强制所有活跃用户,您可以将当前大小分配给全局变量,例如global.R<<-

但是,您可能需要一个需要身份验证的每用户设置。这还不可行,但请在闪亮的论坛上查看Jeff Allens comment

答案 1 :(得分:1)

在@Joe Cheng之后,我重新阅读了范围界定章,并指出我以前总是弄错了。这是更简单的版本;我删除了旧的以避免混淆,抱歉犯错误。

server.R

shinyServer(function(input, output, session) {
  maxx = 1
  maxy = 1
  output$simpleplot <- renderPlot({
    input$nextButton # create dependency on action button
    scalex = round(runif(1,0.1,1),2)
    scaley = round(runif(1,0.1,1),2)
    fix = isolate(input$fixscale)

    if (fix){
      plot(runif(100,0,scalex),runif(100,0,scaley),pch=16,cex=0.5,
           xlim= c(0,maxx), ylim=c(0,maxy))

    } else {
      maxx <<- scalex
      maxy <<- scaley
      updateNumericInput(session,"maxx", value=scalex)
      updateNumericInput(session,"maxy", value=scaley)
      plot(runif(100,0,scalex),runif(100,0,scaley),pch=16,cex=0.5,
           col="red")    
    }  
  })
})

ui.r

shinyUI(pageWithSidebar(
  headerPanel("FixScale Test"),
  sidebarPanel(
    checkboxInput("fixscale", "Fix Scale", FALSE),
    actionButton("nextButton", "Next"),
    br()
  ),
  mainPanel(
    plotOutput("simpleplot")
  )
))