闪亮:ggplot 的动态颜色(填充)输入

Shiny: Dynamic colour (fill) input for ggplot

我确实需要一些帮助,因为 post: Dynamic color input in shiny server 没有给出我的问题的完整答案。

我想在我闪亮的应用程序中选择动态颜色(填充)。我准备了示例代码:

library(shiny)
library(shinyjs)
library(reshape2)
library(ggplot2)

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

runApp(shinyApp(
  ui = fluidPage(
    selectizeInput("select","Select:", choices=as.list(levels(dat$variable)), selected="X1",multiple =TRUE),
    uiOutput('myPanel'),
    plotOutput("plot"),
    downloadButton('downloadplot',label='Download Plot')
  ),
  server = function(input, output, session) {
    cols <- reactive({
      lapply(seq_along(unique(input$select)), function(i) {
        colourInput(paste("col", i, sep="_"), "Choose colour:", "black")        
      })
    })

    output$myPanel <- renderUI({cols()})

    cols2 <- reactive({        
      if (is.null(input$col_1)) {
        cols <- rep("#000000", length(input$select))
      } else {
        cols <- unlist(colors())
      }
      cols})

    testplot <- function(){
      dat <- dat[dat$variable %in% input$select, ]
      ggplot(dat, aes(x=variable,y=value, fill=cols2()[1])) + geom_boxplot()}

    output$plot <- renderPlot({testplot()})

    output$downloadplot <- downloadHandler(
      filename ="plot.pdf",
      content = function(file) {
        pdf(file, width=12, height=6.3)
        print(testplot())
        dev.off()
      })
  }
))

我希望用户选择箱线图的填充颜色。颜色小部件的数量将根据 selectizeInput("select"... 中所选变量的数量出现。到目前为止一切都运行良好,但是更进一步我无法弄清楚如何将这种颜色应用到 ggplot 等...

这是我的问题:

  1. 如何将填充颜色正确连接到 ggplot

  2. 我能否使 colourInput() 默认颜色对应于默认调色板(不是一种颜色 --> 在我的例子中是黑色)

  3. 而不是colourInput(paste("col", i, sep="_"), "Choose colour:",中选择颜色文本我希望有相应的名称(从selectizeInput中选择变量)变量(在本例中为 X1、X2 和 X3)

  4. 我也想要一个可以重置所有所选颜色的按钮

先谢谢大家,希望能解决这个问题

干杯

这些都是非常好的和具体的问题,我很高兴,希望能回答他们:)

  1. How i can connect the fill colour to ggplot correctly

在这种情况下,我认为最好的方法是根据 variable(反应式)填充框并添加一个新层 scale_fill_manual,您可以在其中指定自定义颜色不同的盒子。颜色的数量必须明显等于 variable 的级别数。这可能是最好的方法,因为您将始终拥有正确的图例。

ggplot(dat, aes(x = variable, y = value, fill = variable)) + 
          geom_boxplot() +
          scale_fill_manual(values = cols)

  1. Can i make the default colour of colourInput() correspond to the default colour palette (not to one colour --> in my case is black)

当然可以。

首先,您需要了解 ggplot 使用的离散变量的默认颜色。为了生成这些颜色,我们将使用 this 中的一个函数 gg_color_hue nice discussion。我已将其名称更改为 gg_fill_hue 以遵循 ggplot 约定。

我们可以在 renderUI 中对所有内容进行编码,其中我们首先指定选定的 levels/variables。为了消除由于动态(并且可能以不同的顺序)生成的小部件而导致的明确性,我们对 levels/variables.

的名称进行排序

然后我们使用 gg_fil_hue 生成适当数量的默认颜色并将它们分配给适当的小部件。

为了方便起见,我们将这些小部件的 IDs 更改为 col + "varname",由 input$select

给出
output$myPanel <- renderUI({ 
      lev <- sort(unique(input$select)) # sorting so that "things" are unambigious
      cols <- gg_fill_hue(length(lev))

      # New IDs "colX1" so that it partly coincide with input$select...
      lapply(seq_along(lev), function(i) {
        colourInput(inputId = paste0("col", lev[i]),
                    label = paste0("Choose colour for ", lev[i]), 
                    value = cols[i]
        )        
      })
    })

3.Instead of Choose colour text in colourInput(paste("col", i, sep="_"), "Choose colour:", i would love to have the corresponding name (choosen variable from selectizeInput) of the variable (in this case X1, X2 and X3)

上面的代码也是这么干的——简单的粘贴。


现在,让我们来看看由于生成的小部件的动态数量而出现的一个非常重要的问题。我们必须根据唯一的 colorInput 设置框的颜色,这些输入可能有 1,2 甚至 10 个。

我认为,解决这个问题的一个很好的方法是创建一个字符向量,其中包含指定我们通常如何访问这些小部件的元素。在下面的示例中,此向量如下所示:c("input$X1", "input$X2", ...).

然后使用非标准评估(evalparse)我们可以评估这些输入以获得具有选定颜色的向量,然后我们将其传递给 scale_fill_manual 层。

为了防止选择之间可能出现的错误,我们将使用函数“req”来确保带有颜色的矢量的长度与所选矢量的长度相同levels/variables。

output$plot <- renderPlot({
        cols <- paste0("c(", paste0("input$col", sort(input$select), collapse = ", "), ")")
        # print(cols)
        cols <- eval(parse(text = cols))
        # print(cols)

        # To prevent errors
        req(length(cols) == length(input$select))

        dat <- dat[dat$variable %in% input$select, ]
        ggplot(dat, aes(x = variable, y = value, fill = variable)) + 
          geom_boxplot() +
          scale_fill_manual(values = cols)

    })

  1. I would like as well to have a button which could reset all the choosen colours

在客户端用 ID="reset" 定义 actionButton 之后,我们创建了一个将要更新 colorInput 的观察者。

我们的目标是 return 一个包含 updateColourInput 的列表,其中每个可用的 colourInput 小部件都有适当的参数化。

我们定义一个包含所有选择的变量 levels/variables 并生成适当数量的默认颜色。我们再次对向量进行排序以避免歧义。

然后我们使用 lapplydo.call 调用一个 updateColourInput 函数,指定的参数以列表的形式给出。

observeEvent(input$reset, {
      # Problem: dynamic number of widgets
      # - lapply, do.call

      lev <- sort(unique(input$select))
      cols <- gg_fill_hue(length(lev))

      lapply(seq_along(lev), function(i) {
              do.call(what = "updateColourInput",
                      args = list(
                        session = session,
                        inputId = paste0("col", lev[i]),
                        value = cols[i]
                      )
              )
      })
    })

完整示例:

library(shiny)
library(shinyjs)
library(reshape2)
library(ggplot2)

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

# Function that produces default gg-colours is taken from this discussion:
# 
gg_fill_hue <- function(n) {
  hues = seq(15, 375, length = n + 1)
  hcl(h = hues, l = 65, c = 100)[1:n]
}

runApp(shinyApp(
  ui = fluidPage(
    selectizeInput("select", "Select:", 
                   choices = as.list(levels(dat$variable)), 
                   selected = "X1", 
                   multiple = TRUE), 
    uiOutput('myPanel'),
    plotOutput("plot"),
    downloadButton('downloadplot', label = 'Download Plot'),
    actionButton("reset", "Default colours", icon = icon("undo"))
  ),
  server = function(input, output, session) {

    output$myPanel <- renderUI({ 
      lev <- sort(unique(input$select)) # sorting so that "things" are unambigious
      cols <- gg_fill_hue(length(lev))

      # New IDs "colX1" so that it partly coincide with input$select...
      lapply(seq_along(lev), function(i) {
        colourInput(inputId = paste0("col", lev[i]),
                    label = paste0("Choose colour for ", lev[i]), 
                    value = cols[i]
        )        
      })
    })


    output$plot <- renderPlot({
      cols <- paste0("c(", paste0("input$col", sort(input$select), collapse = ", "), ")")
      # print(cols)
      cols <- eval(parse(text = cols))
      # print(cols)

      # To prevent errors
      req(length(cols) == length(input$select))

      dat <- dat[dat$variable %in% input$select, ]
      ggplot(dat, aes(x = variable, y = value, fill = variable)) + 
        geom_boxplot() +
        scale_fill_manual(values = cols)

    })


    observeEvent(input$reset, {
      # Problem: dynamic number of widgets
      # - lapply, do.call

      lev <- sort(unique(input$select))
      cols <- gg_fill_hue(length(lev))

      lapply(seq_along(lev), function(i) {
        do.call(what = "updateColourInput",
                args = list(
                  session = session,
                  inputId = paste0("col", lev[i]),
                  value = cols[i]
                )
        )
      })
    })




    output$downloadplot <- downloadHandler(
      filename = "plot.pdf",
      content = function(file) {
        pdf(file, width = 12, height = 6.3)
        print(testplot())
        dev.off()
      })
  }
))