gpt4 book ai didi

r - 在基于 HTML 模板的 Shiny App 中使用 Plotly 失败

转载 作者:行者123 更新时间:2023-12-01 13:48:58 26 4
gpt4 key购买 nike

我正在构建一个基于 HTML 模板的 Shiny 应用程序,我想将 plotly 用于图表。我正在努力将图表插入模板。

以下代码工作正常:

library(shiny)
library(plotly)

shinyApp(

ui <- fluidPage(plotlyOutput("plot1")),

server <- function(input, output) {

p <- plot_ly(mtcars, x = ~mpg, y = ~wt, type = 'scatter', mode = 'markers')

output$plot1 <- renderPlotly({p})

}
)

但是当我将应用程序更改为使用模板时,我也无法使用 renderPlotly 来做到这一点。也不是 renderUI .
<!doctype html>
<html lang="en">
<head>
<script src="shared/jquery.js" type="text/javascript"></script>
<script src="shared/shiny.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="shared/shiny.css"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="w3.css">
</head>

<body>

<h1>HTML Template UI</h1>
<div id="plot1" class="shiny-plot-output" style="width: 100%; height: 300px; border: 1px solid red"></div>
<div id="plot2" class="shiny-html-output" style="width: 100%; height: 300px; border: 1px solid blue"></div>

</body>
</html>

应用程序
library(shiny)
library(plotly)

shinyApp(

ui <- htmlTemplate("template.html"),

server <- function(input, output) {

p <- plot_ly(mtcars, x = ~mpg, y = ~wt)

output$plot1 <- renderPlotly({p})

output$plot2 <- renderUI(HTML(paste(htmltools::tagList(list(p)))))

}
)

有没有办法在基于 HTML 模板的 Shiny 应用程序中使用 plotly?

最佳答案

有一种更优雅、更简单的方法来实现这一点。在这个 RStudio article 中有很好的描述.

要包含必要的 HTML 和 JS 依赖项,请包含 headContent()在 htmlTemplate 的标题中。如果您需要 Bootstrap 组件(actionButtons、tabsetPanel),您还必须包含 bootstrapLib()在标题中。确保这些命令在双大括号内,如
{{ bootstrapLib() }} .

您还可以在这样的大括号中放置代码以生成输入和输出(如 plotly),这将自动创建 html 组件并为您包含 JavaScript 依赖项。

这使得 template.html 更加干净。

模板.html

<!doctype html>
<html lang="en">
<head>

{{ headContent() }}

</head>
<body>
<h1>HTML Template UI</h1>
<div class="container-fluid">

{{plotlyOutput("plot1") }}
{{uiOutput("plot2") }}

</div>
</body>
</html>

app.R
library(shiny)
library(plotly)

p <- plot_ly(mtcars, x = ~mpg, y = ~wt, type = 'scatter', mode = 'markers')

ui <- htmlTemplate("template.html")

server <- function(input, output) {
output$plot1 <- renderPlotly({p})
output$plot2 <- renderUI(HTML(paste(htmltools::tagList(list(p)))))
}

关于r - 在基于 HTML 模板的 Shiny App 中使用 Plotly 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48949921/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com