首页 > 解决方案 > 如何保存一个ggplot,使其可以完全占据一个固定高度和宽度的div作为背景

问题描述

我想创建一个Shiny应用程序,其中background pictureadiv将是ggplot之前保存的一些图表。下面是一个这样的原型 -

library(shiny)
library(ggplot2)

# create and save plot
if (!file.exists("www")) dir.create("www")
ggsave(filename = "www/Some_Plot.png",
        ggplot(mpg, aes(class)) + geom_bar(),
        device = 'png')

shinyApp(
  ui = fluidPage(
    div(style = "height: 550px; width: 550px; background: url('www/Some_Plot.png') no-repeat center center; background-size: cover;")
  ),
  server = function(input, output) {

  }
)

鉴于heightwidthdiv我想拥有它的背景,因为它应该在维护的同时gg-plot占据整个。divaspect ratio

任何如何实现这一点的指针都将非常有帮助。

谢谢,

标签: rggplot2shinyshinyapps

解决方案


我不知道为什么,但是我无法在您的示例中使用它,而是在我自己的小示例中使用它。对于那个很抱歉。

我删除了对目录的检查。据推测,您只会这样做一次,并且在设置应用程序时会这样做。

似乎让它工作的关键在于您应用的 CSS 样式。默认情况下, Shiny 应用程序会在www文件夹中查找,因此在样式中指定它意味着 Shiny 无法找到图像。如果您查看我的示例,我只调用文件名,因为它已经放置在正确的文件夹中。

# Load packages ----
pkgs <- c("shiny", "ggplot2")
invisible(lapply(pkgs, require, character.only = TRUE))

# Generate a plot ----
some_plot <- ggplot(mpg, aes(class)) +
  geom_bar()

ggsave(
  "www/some-plot.png",
  some_plot,
  device = "png"
)

# Define the user interface ----
ui <- fluidPage(
  div(
    style = "height: 550px; width = 550px;
             background: url('some-plot.png') no-repeat center center;
             background-size: cover;"
  )
)

# Define the server side ----
server <- function(input, output, session) {

}

# Combine into an app ----
shinyApp(ui = ui, server = server)

我确实删除了文件,重新启动 RStudio 并重新运行了应用程序,它能够创建图像并使用 CSS 样式将其渲染为背景。请尝试使用您的代码(修改过的 ofc)和我的代码。也许我在修改您的代码时做了一些不正确的事情,或者您发现了我错过的内容。


推荐阅读