【问题标题】:Shiny in R: Is it possible to output a color using renderText?R 中的闪亮:是否可以使用 renderText 输出颜色?
【发布时间】:2017-01-12 22:46:43
【问题描述】:

我正在尝试使用包 shinydashboard 创建一个框。我无法在服务器端创建它(这是另一个问题,但在我的问题上)。但是,我想动态设置颜色,想知道是否可以通过使用 renderText 来实现。我现在在服务器端有一个 renderText,它输出 NULL 或颜色“栗色”。但是,这给了我以下错误:

Warning: Error in validateColor: Invalid color

您知道问题出在哪里或有不同的方法吗?非常感谢任何帮助!

【问题讨论】:

  • 看看shijyjs package 我觉得这就是你想要的。 github.com/daattali/shinyjs
  • @猪排。非常感谢 - 这看起来很有希望。你有经验吗?我为盒子创建了一个 div(和一个 id)并使用了切换类。但是,它没有反应。此外,我定义了 inlineCSS(list(.maroon = "background-color: maroon")),

标签: r shiny shinydashboard


【解决方案1】:

简而言之,无法使用renderText 直接更改颜色,但有很多方法可以动态更改文本颜色。

举几个方法,你可以:

使用 CSS 类并在它们之间切换:

require(shiny)
require(shinydashboard)

ui <- dashboardPage(
  dashboardHeader(title = "Basic dashboard"),
  dashboardSidebar(),
  dashboardBody(
    tags$head(
      tags$style(
        HTML("
              .toggle{
                color: red;
              }
             ")
        ),
      tags$script(
        HTML("
          Shiny.addCustomMessageHandler ('toggleClass',function (m) {
                  var element = $('#'+m.id); // Find element to change color of
                  element.toggleClass('toggle');
          });
             ")
      )
    ),
    fluidRow(
      box( id='test',
           title = "Box",
           status = "warning",
           solidHeader = TRUE,
           height = 400,
           textOutput('txtOut')
      )
    ),
    actionButton('btn','Generate Color')
  ) #end dashboardBody
)

server <- function(input, output, session) {

  # Helper function, calls javascript
  toggleClass <- function(id){
    session$sendCustomMessage(type = 'toggleClass', message = list('id'=id))
  }

  output$txtOut <- renderText({ "Static text" }); # Text can be re-rendered independantly

  observeEvent(input$btn,{
    toggleClass('txtOut') # Add  / remove class
  })

}
shinyApp(ui, server)

使用 Javascript 绑定来改变元素的颜色(可能是最强大的方法):

   require(shiny)
   require(shinydashboard)

    ui <- dashboardPage(
      dashboardHeader(title = "Basic dashboard"),
      dashboardSidebar(),
      dashboardBody(
        tags$head(
          tags$script(
            HTML("
              // Change color inside of element with supplied id
              Shiny.addCustomMessageHandler ('changeTxtColor',function (m) {
                      var element = $('#'+m.id); // Find element to change color of
                      element.css({ 'color': 'rgb('+m.r+','+m.g+','+m.b+')' }); // Change color of element
              });

              // Change color of shinydashboard box
              Shiny.addCustomMessageHandler ('changeBoxColor',function (m) {
                      var parent  = $('#'+m.id).closest('.box');
                      var element = parent.children('.box-header');
                      var rgbStr  = 'rgb('+m.r+','+m.g+','+m.b+')';
                      element.css({ 'background-color':  rgbStr});
                      parent.css({ 'border-color' :  rgbStr})
              });
                ")
          )
        ),
        fluidRow(
          box( id='test',
            title = "Box",
            status = "warning",
            solidHeader = TRUE,
            height = 400,
            textOutput('txtOut'),
            div(id='target') 
            # Since you can't specify the id of shinydashboard boxes
            # we need a child with id to change the color of the box.
          )
        ),
        actionButton('btn','Generate Color')
      )
    )

    server <- function(input, output, session) {

      randomColor <- reactive({
        input$btn
        name <- sample(colors(),1)
        rgb  <- col2rgb(name)
        return( list(name=name, rgb=rgb) )
      })

      # Helper function, calls javascript
      changeTxtColor <- function(id,rgb){
        session$sendCustomMessage(type = 'changeTxtColor', message = list('id'=id,'r'=rgb[1],'g'=rgb[2],'b'=rgb[3]))
      }
      changeBoxColor <- function(id,rgb){
        session$sendCustomMessage(type = 'changeBoxColor', message = list('id'=id,'r'=rgb[1],'g'=rgb[2],'b'=rgb[3]))
      }

      output$txtOut <- renderText({
        rgb <- randomColor()$rgb
        changeTxtColor('txtOut',rgb)
        changeBoxColor('target',rgb)
        sprintf("Generated color with name %s ", randomColor()$name)
      })

    }
    shinyApp(ui, server)

只输出 HTML 而不是使用 renderText,允许精确 控制 HTML 产生看到这个question:

require(shiny)
require(shinydashboard)

ui <- dashboardPage(
  dashboardHeader(title = "Basic dashboard"),
  dashboardSidebar(),
  dashboardBody(
    fluidRow(
      box( id='test',
           title = "Box",
           status = "warning",
           solidHeader = TRUE,
           height = 400,
           htmlOutput('txtOut')
      )
    ),
    actionButton('btn','Generate Color')
  ) #end dashboardBody
)

server <- function(input, output, session) {

  # Reactive variable
  randomColor <- reactive({
    input$btn
    name <- sample(colors(),1)
    rgb  <- col2rgb(name)
    return( list(name=name, rgb=rgb) )
  })

  # Helper function, calls javascript
  toggleClass <- function(id){
    session$sendCustomMessage(type = 'toggleClass', message = list('id'=id))
  }

  output$txtOut <- renderUI({
    rgb    <- randomColor()$rgb
    rgbStr <- sprintf('rgb(%d,%d,%d)',rgb[1],rgb[2],rgb[3])
    print(rgb)
    div( HTML(sprintf("<text style='color:%s'> Generated color with name %s </text>", rgbStr, randomColor()$name) ) )
  })

}
shinyApp(ui, server)

对文本量感到抱歉。

【讨论】:

    猜你喜欢
    • 2021-07-31
    • 1970-01-01
    • 2018-05-13
    • 1970-01-01
    • 2014-05-06
    • 2021-08-29
    • 1970-01-01
    • 1970-01-01
    • 2016-06-28
    相关资源
    最近更新 更多