gpt4 book ai didi

Shiny 应用程序中的 renderImage() 和 .svg

转载 作者:行者123 更新时间:2023-12-02 11:33:47 26 4
gpt4 key购买 nike

我无法使用 renderImage() 来处理 .svg 文件。我的最小示例( adapted from the corresponding RStudio-tutorial ):

ui.R

shinyUI(pageWithSidebar(
headerPanel("renderSVG example"),
sidebarPanel(
sliderInput("obs", "Number of observations:",
min = 0, max = 1000, value = 500),
actionButton("savePlot", "savePlot")
),
mainPanel(
# Use imageOutput to place the image on the page
imageOutput("plot"),
imageOutput("plot_as_svg")
)
))

服务器.R

require("ggplot2")
library(svglite)

shinyServer(function(input, output, session) {

## create plot with renderPlot()


output$plot<- renderPlot({
hist(rnorm(input$obs), main="Generated in renderPlot()")
})


## create .svg file of the plot and render it with renderImage()

output$plot_as_svg <- renderImage({
# A temp file to save the output.
# This file will be removed later by renderImage
outfile <- tempfile(fileext='.svg')

# Generate the svg
svglite(outfile, width=400, height=300)
hist(rnorm(input$obs), main="Generated in renderImage()")
dev.off()

# Return a list containing the filename
list(src = outfile,
contentType = 'text/svg+xml',
width = 400,
height = 300,
alt = "This is alternate text")
}, deleteFile = TRUE)

})

有什么想法问题出在哪里吗?

最佳答案

我也遇到了同样的问题,而且我在网上找不到任何可以解决这个问题的方法,这令人沮丧。这是对我有用的解决方案:

ui.R:

shinyUI(pageWithSidebar(
headerPanel("renderSVG example"),
sidebarPanel(
sliderInput("obs", "Number of observations:",
min = 0, max = 1000, value = 500),
actionButton("savePlot", "savePlot")
),
mainPanel(
# Use imageOutput to place the image on the page
imageOutput("plot"),
imageOutput("plot_as_svg")
)
))

服务器.R:

require("ggplot2")

shinyServer(function(input, output, session) {

## create plot with renderPlot()


output$plot<- renderPlot({
hist(rnorm(input$obs), main="Generated in renderPlot()")
})


## create .svg file of the plot and render it with renderImage()

output$plot_as_svg <- renderImage({

width <- session$clientData$output_plot_width
height <- session$clientData$output_plot_height
mysvgwidth <- width/96
mysvgheight <- height/96

# A temp file to save the output.
# This file will be removed later by renderImage

outfile <- tempfile(fileext='.svg')

# Generate the svg
svg(outfile, width=mysvgwidth, height=mysvgheight)
hist(rnorm(input$obs), main="Generated in renderImage()")
dev.off()

# Return a list containing the filename
list(src = normalizePath(outfile),
contentType = 'image/svg+xml',
width = width,
height = height,
alt = "My Histogram")
})

})

注意,我没有使用 svglite 包,只是使用 grDevices (base) 包中的 svg 设备。我还规范了源代码中的路径,因为我使用的是 Windows 计算机(我相信这会将我的源代码从正斜杠更改为反斜杠,但也许有人会对此发表评论)。

此外,我创建了四个新变量来容纳 svg 宽度和高度以及图像宽度和高度,以便仍然与页面保持流畅。我确信有比这更简单的解决方法,但我发现这是有效的。

关于 Shiny 应用程序中的 renderImage() 和 .svg,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39093777/

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