【发布时间】:2017-01-27 01:56:49
【问题描述】:
我正在设计一个完全动态的用户界面,目的是用闪亮的方式进行演示。我的清单上有几个步骤,我正在一步一步地工作。
- 自定义由函数'checkboxGroupInput'生成的多选框的背景颜色
- make the checkboxes more dynamic -- when the background color will be on/off when select/de-select one checkbox
我在另一篇文章中找到了解决方案,并且效果很好。 (how to make the checkboxgroupinput color-coded in Shiny) 这是我得到的代码:
my_checkboxGroupInput <- function(variable, label, choices, selected, colors){
choices_names <- choices
if(length(names(choices))>0) my_names <- names(choices)
div(id=variable,class="form-group shiny-input-checkboxgroup shiny-input-container shiny-bound-input",
HTML(paste0('<label class="control-label" for="',variable,'">',label,'</label>')),
div( class="shiny-options-group",
HTML(paste0('<div class="checkbox" style="color:', colors,'">',
'<label>',
'<input type="checkbox" name="', variable,
'" value="', choices,
'"', ifelse(choices %in% selected, 'checked="checked"', ''),
'/>',
'<span>', choices_names,'</span>',
'</label>',
'</div>', collapse = " "))
)
)
}
library(shiny)
my_names <- c('one'=1,'two'=2,'three'=3)
my_selected <- c(1,2)
my_colors <-c('blue','red','green')
shinyApp(
ui=fluidPage(uiOutput("my_cbgi")),
server = function(input, output, session) {
output$my_cbgi <- renderUI(my_checkboxGroupInput("variable", "Variable:",
choices = my_names,
selected=my_selected,
colors=my_colors))
}
)
现在,我想要更动态的东西——而不是永久地将颜色分配给一个选项,我更喜欢将前 N 个颜色分配给 N 个选择的项目。不幸的是,我自定义的代码没有按我想要的方式工作。
例如,我有 6 种颜色,并且默认选择了所有六个变量,当我取消选中(二、三、四、五)中的任何一个时,我假设取消选中后的颜色会更新适当地。假设 ('blue','red','green','purple','lemon','brown') AND ('one','two','three' ,'四','五','六');当我取消选中“三”时,我想看到 ('blue','red','green','purple','lemon') for ('one','two', 'four','five','six'),但实际颜色是('blue','red','purple','lemon','blue')。
这是我用来测试的代码:
my_names <- c('one','two','three','four','five','six')
my_selected <- c('one','two','three','four','five','six')
my_colors <-c('blue','red','green','purple','lemon','brown')
shinyApp(ui=fluidPage(uiOutput("my_cbgi")),
server = function(input, output, session) {
my <- reactiveValues(selected=my_selected)
observeEvent(input$variable,{my$selected <- input$variable})
output$my_cbgi <- renderUI(my_checkboxGroupInput("variable", "Variable:",
choices = my_names,
selected=my$selected,
colors=my_colors[1:length(my$selected)]))
})
【问题讨论】:
-
@HubertL 完成!谢谢。
-
我无法想象你为什么要这样做
标签: colors background shiny