您可能想要使用reactiveValues
and observeEvent
。
library(shiny)
library(colourpicker)
ui <- fluidPage(
colourInput('col', 'Select colour', 'purple'),
actionButton(inputId = 'OK', label = 'enter color'),
textOutput('couleurs')
)
server <- function(input, output) {
values <- reactiveValues(col_string = '')
observeEvent(input$OK, {
if (values$col_string == '') {
values$col_string <- paste0('"', input$col, '"')
} else {
values$col_string <- paste0(values$col_string, ', ', paste0('"', input$col, '"'))
}
})
output$couleurs <- renderText({ values$col_string })
}
shinyApp(ui = ui, server = server)
这是一个在 sankey 网络中使用所选颜色的示例。正如我在评论中所说,您将不得不使用paste0
or 的sep = ""
参数,paste
以便组合在一起的元素colorJS
不会被空格分隔。这就是为什么我问你粘贴命令的输出是什么。请注意这两个命令及其输出之间的区别...
domain <- '"one", "two", "three"'
col_string <- '"#382743", "#916402", "#064713"'
paste('d3.scaleOrdinal().domain([', domain, '])', '.range([', col_string, '])')
# d3.scaleOrdinal().domain([ "one", "two", "three" ]) .range([ "#382743", "#916402", "#064713" ])
paste0('d3.scaleOrdinal().domain([', domain, '])', '.range([', col_string, '])')
# d3.scaleOrdinal().domain(["one", "two", "three"]).range(["#382743", "#916402", "#064713"])
这是最小的可重现示例(不需要除您之外没有人可以访问的特殊格式的 Excel 电子表格)...
library(shiny)
library(colourpicker)
library(networkD3)
ui <- fluidPage(
colourInput('col', 'Select colour', 'purple'),
actionButton(inputId = 'OK', label = 'enter color'),
textOutput('couleurs'),
actionButton(inputId = 'plot', label = 'plot'),
sankeyNetworkOutput("splot")
)
server <- function(input, output) {
values <- reactiveValues(col_string = '')
observeEvent(input$OK, {
if (values$col_string == '') {
values$col_string <- paste0('"', input$col, '"')
} else {
values$col_string <- paste0(values$col_string, ', ', paste0('"', input$col, '"'))
}
})
output$couleurs <- renderText({ values$col_string })
observeEvent(input$plot, {
if (values$col_string != '') {
output$splot <- renderSankeyNetwork({
data <- data.frame(i = c(0, 0, 0),
j = c(1, 2, 3),
value = c(3, 1, 2),
lgroup = c("lgroup1", "lgroup2", "lgroup2"))
label <- data.frame(name = c("zero", "one", "two", "three"),
ngroup = c("ngroup1", "ngroup2", "ngroup2", "ngroup2"))
domain <- paste0("'", paste(unique(c(as.character(data$lgroup), as.character(label$ngroup))), collapse = "', '"), "'")
colorJS <-
paste0('d3.scaleOrdinal().domain([', domain, ']).range([', values$col_string, '])')
sankeyNetwork(Links = data, Nodes = label, Source = 'i', Target = 'j',
Value = 'value', NodeID = "name", NodeGroup = "ngroup",
LinkGroup = "lgroup", colourScale = colorJS)
})
}
})
}
shinyApp(ui = ui, server = server)