r - 如何保存一个ggplot,使其可以完全占据一个固定高度和宽度的div作为背景
问题描述
我想创建一个Shiny
应用程序,其中background picture
adiv
将是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) {
}
)
鉴于height
和width
,div
我想拥有它的背景,因为它应该在维护的同时gg-plot
占据整个。div
aspect ratio
任何如何实现这一点的指针都将非常有帮助。
谢谢,
解决方案
我不知道为什么,但是我无法在您的示例中使用它,而是在我自己的小示例中使用它。对于那个很抱歉。
我删除了对目录的检查。据推测,您只会这样做一次,并且在设置应用程序时会这样做。
似乎让它工作的关键在于您应用的 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)和我的代码。也许我在修改您的代码时做了一些不正确的事情,或者您发现了我错过的内容。
推荐阅读
- php - 如何建立一个基于 PHP WOL(wake on lan) 的网站
- c++ - 如何对包含CString的类向量进行排序?
- python-3.x - 'Fata Error':Python 可执行文件抛出错误
- python - 如何使用python处理将值添加到具有现有值的txt文件的第一行
- jsreport - 用 jsreport-core 添加很多行
- python - 检查任何 Html 标签中是否存在属性 Selenium Python
- python - 我如何推导出这部分算法
- vba - 数据透视表 0 个总计错过了
- sql - 为什么我的 FOREIGN KEY 约束不起作用:为什么插入的外部列中不存在值?
- python-3.x - 有没有办法在 python 中扫描整个网络范围(192.168.0./24)并将数据输出到文本文件?