R Shiny - using log scale slider for values from 0

2019-09-06 13:00发布

I'm trying to set up a shiny slider with a log base 10 scale from 0.01 to 100. I've been using this Q/A to try to solve my issue. However I can't seem to get the horizontal lines on the plot to react according to the slider thresholds.

Am I missing something?

The image shows my slider and the lines drawn on the plot; neither the bottom or top thresholds match the horizontal line positions. If I revert to a linear scale the lines do match the slider positions.

my reproducible code

# Set libraries
library(shiny)
library(ggplot2)

# Global variables
from <- seq(1, 100, 1)
data <- (rexp(100, 0.05))
df1 <- as.data.frame(cbind(from, data))

JScode <-
  "$(function() {
setTimeout(function(){
var vals = [0];
var powStart = -2;
var powStop = 2;
for (i = powStart; i <= powStop; i++) {
var val = Math.pow(10, i);
val = parseFloat(val.toFixed(8));
vals.push(val);
}
$('#slider1').data('ionRangeSlider').update({'values':vals})
}, 10)})"

ui <-
  shinyUI(fluidPage(tabsetPanel(tabPanel(
    "", " ",
    fluidRow(
      column(
        width = 6,
        tags$head(tags$script(HTML(JScode))),
        sliderInput(
          "slider1",
          "bounds",
          min = 0,
          max = 100,
          value = c(0, 100)
        )
      ),
      column(width = 6, " ",
             plotOutput("plot7"))
    )
  ))))

server <- function(input, output) {
  filedata <- reactive({
    infile <- input$datafile
    if (is.null(infile)) {
      return(df1) # this returns the default .Rds - see global variables
    }
    temp <- read.csv(infile$datapath)
    #return
    temp[order(temp[, 1]),]
  })
  output$plot7 <- renderPlot({
    ggplot(df1, aes(sample = data)) +
      stat_qq() +
      scale_y_log10() +
      geom_hline(aes(yintercept = input$slider1[1])) + # low bound
      geom_hline(aes(yintercept = input$slider1[2])) + # high bound
      labs(title = "Q-Q Plot", x = "Normal Theoretical Quantiles", y = "Normal Data Quantiles")
  })
}

shinyApp(ui = ui, server = server)

Image enter image description here

1条回答
成全新的幸福
2楼-- · 2019-09-06 13:37

I post an answer because the comment section is too limited. To extract the error, I checked which values the JScode will output. The values are seq(-2, 2, 1). Therefore you need to calculate the "real" values (e.g. 1,10,100) using 10^x:

Here the complete render plot function:

output$plot7 <- renderPlot({
  ggplot(df1, aes(sample = data)) +
   stat_qq() +
   scale_y_log10(limits = c(0.01,100)) + # set limits to plot reproducible images
   geom_hline(aes(yintercept = c(0,10^seq(-2,2))[input$slider1[1]+1])) + # low bound
   geom_hline(aes(yintercept = c(0,10^seq(-2,2))[input$slider1[2]+1])) + # high bound
   labs(title = "Q-Q Plot", x = "Normal Theoretical Quantiles", y = "Normal Data Quantiles")
})
查看更多
登录 后发表回答