我有一个闪亮的应用程序,每当我单击按钮时,它就会向应用程序添加 gridstack.js gridstack 面板。现在,我想向面板添加一个绘图。 这是我的代码:
library(shinydashboard)
library(shiny)
library(shinyjs)
library(shinyjqui)
library(gridstackeR)
library(plotly)
ui <- fluidPage (
useShinyjs(),
includeCSS("www/app.css"),
tags$head(
tags$script(src = "https://cdnjs.cloudflare.com/ajax/libs/gridstack.js/10.0.1/gridstack-all.min.js", type='module'),
tags$script(HTML('
function addFirstWidget() {
var grid = document.querySelector(\'.grid-stack\').gridstack;
grid.addWidget({h:5, w: 2, content: \'This is where the plot goes\'});
}
'))
),
grid_stack(id="mygrid"),
actionButton("first_widget", "First Widget"),
title = "Gridstack Prototype"
)
server <- function(input, output, session) {
observeEvent(input$first_widget, {
# browser()
runjs("addFirstWidget();")
})
}
shinyApp(ui = ui, server = server)
每当按下按钮时,JS 函数 addFirstWidget() 都会创建一个新的 gridstack 面板。
我想调用一个在面板中的plotly、ggplot或其他绘图库中渲染绘图的函数(我会知道我用于绘图的库),例如,这个:
plot_ly(data = iris, x = ~Sepal.Length, y = ~Petal.Length)
但是,我不确定如何实际将这个交互式图放入面板中。必须保持交互性,而且我不能用JS来生成图
您不必包含 JavaScript 库,因为它包含在 R 包中。
这是一种使用
insertUI
的方法。但你必须在 UI 中给出 w
和 h
。我首先尝试插入grid_stack_item(plotlyOutput(......
,但这不太好。
library(shiny)
library(gridstackeR)
library(plotly)
ui <- fluidPage(
grid_stack(
id = "mygrid",
grid_stack_item(
id = "widget1",
w = 6, h = 6
)
),
actionButton("first_widget", "First Widget"),
title = "Gridstack Prototype"
)
server <- function(input, output, session) {
output$pltly <- renderPlotly({
plot_ly(data = iris, x = ~Sepal.Length, y = ~Petal.Length)
})
observeEvent(input$first_widget, {
insertUI(
"#widget1",
where = "afterBegin",
plotlyOutput("pltly")
)
})
}
shinyApp(ui = ui, server = server)