首页 文章

闪亮服务器中的动态颜色输入

提问于
浏览
4

我正在尝试使用Shiny创建一个应用程序,我希望用户能够选择绘图中每一行的颜色 . 一般的想法是在应用程序中导入数据,然后在数据中绘制每个变量 . 我尝试使用shinysky软件包中的colorpicker'jscolorInput',当放在ui.r文件中时,它可以正常工作,但由于我希望我的应用程序对于每个上传的数据集都是动态的,我需要将颜色选择器放在服务器中 . R,使用反应函数 . 当放在服务器中时,'jscolorInput'不起作用 .

我想做的是:

  • 重现颜色选择器的次数与数据中的变量数一样多

  • 从颜色中获取输入并将其作为颜色参数传递给绘图

我在闪亮的开发和stackoverflow都是新手,所以请原谅我的错误 .

这是一个可重复的示例,不起作用 .

require(shinysky)
require(shiny)

dat <- data.frame(matrix(rnorm(120, 2, 3), ncol=3))

runApp(list(
ui = bootstrapPage(
    # The reactive colorpicker
    uiOutput('myPanel'),
    # The plot
    plotOutput('plot')
),
server = function(input, output) {
    # Print as many colorpickers as the columns in the dataset
    cols <- reactive({
        n <- ncol(dat)
        for(i in 1:n){
            print(jscolorInput(paste("col", i, sep="_")))    
        }
    })

        output$myPanel <- renderPrint({cols()})
    # Put all the input in a vector
    colors <- reactive({
        n <- ncol(dat)
        lapply(1:n, function(i) {
            input[[paste("col", i, sep="_")]]
        })
    })

    output$plot <- renderPlot({
        cols <- ifelse(is.null(input$col_1), rep("000000 ", n), colors()) 
        plot(dat[,1], col= paste0("#", cols[1], ""))
                                for(i in 2:ncol(dat))lines(dat[,i], col=cols[i])
    })

}
))

1 回答

  • 2

    这是您正在尝试做的工作版本 . 看看我们的代码之间的差异,你的代码有一些问题 . 此外,请注意我没有使用 shinysky ,因为它没有't have the colourpicker anymore (it'使用shinyjsshinyjs移动到's inactive), so instead I'的另一个包 .

    library(shiny)
    library(shinyjs)
    
    dat <- data.frame(matrix(rnorm(120, 2, 3), ncol=3))
    
    runApp(shinyApp(
      ui = fluidPage(
        uiOutput('myPanel'),
        plotOutput("plot")
      ),
      server = function(input, output, session) {
        cols <- reactive({
          lapply(seq_along(dat), function(i) {
            colourInput(paste("col", i, sep="_"), "Choose colour:", "black")        
          })
        })
    
        output$myPanel <- renderUI({cols()})
    
        # Put all the input in a vector
        colors <- reactive({
          lapply(seq_along(dat), function(i) {
            input[[paste("col", i, sep="_")]]
          })
        })
    
        output$plot <- renderPlot({
          if (is.null(input$col_1)) {
            cols <- rep("#000000", ncol(dat))
          } else {
            cols <- unlist(colors())
          }
          plot(dat[,1], col = cols[1])
          for(i in 2:ncol(dat)) lines(dat[,i], col = cols[i])
        })
      }
    ))
    

    免责声明:我是 shinyjs 的作者

相关问题