【问题标题】:How to save ggrough chart as .png如何将ggrough图表保存为.png
【发布时间】:2019-11-11 00:41:48
【问题描述】:

假设我正在使用Rggrough (https://xvrdm.github.io/ggrough/)。我有这段代码(取自该网页):

library(ggplot2)
library(ggrough)
count(mtcars, carb) %>%
    ggplot(aes(carb, n)) +
    geom_col() + 
    labs(title="Number of cars by carburator count") + 
    theme_grey(base_size = 16) -> p 
options <- list(
    Background=list(roughness=8),
    GeomCol=list(fill_style="zigzag", angle_noise=0.5, fill_weight=2))

然后我可以创建图表(我正在使用 RStudio):

get_rough_chart(p, options)

但是,我可以使用什么代码将其保存为 .png 文件?我正在尝试:

png("ggrough.png")
get_rough_chart(p, options)
dev.off()

我也试过了:

x11()
get_rough_chart(p, options)

但这也不起作用(即使它确实在 x11 窗口中渲染,我也不知道如何将其保存为 .png。

我应该怎么做才能将ggrough 图保存为 .png?

【问题讨论】:

  • 请注意,基于stackoverflow.com/questions/56817718/…,我尝试了:a&lt;- get_rough_chart(p, options, family="Rock Salt", font_size_booster = 1.4) saveWidget(a, "remplot.html") webshot("remplot.html", "remplot.png") HTML 页面正常工作,但屏幕截图显示为空白页面。
  • 可能是ggsave()?
  • 我刚试过ggsave(),但得到了这个错误:'UseMethod(“grid.draw”)错误:'grid.draw'没有适用的方法应用于类“c( 'ggrough', 'htmlwidget')"'

标签: r ggplot2 rstudio png x11


【解决方案1】:

ggrough 情节本质上是htmlwidget,所以我认为典型的图像保存代码不会起作用。

如前所述,您可以通过htmlwidgets::saveWidget(rough_chart_object, "rough_chart.html")htmlwidgets 保存到磁盘。这将创建一个带有 html canvas 元素的 html 文件,该元素是通过嵌入的 javascript 绘制的。正如您所注意到的,webshot::webshot() 由于某种原因无法捕获图像,我也尚未弄清楚。

因为 html 文件在 Chrome 中可以正确呈现,所以我编写了这种 RSelenium 方法。但是,RSelenium 运行所有的相互依赖关系可能会很痛苦,并且通过这种方法创建的图像可能需要后处理。也就是说,由于绘图没有填满整个画布元素,因此图像包含很多不希望出现的空白。

但我将把这种方法留给其他人考虑。

library(dplyr)
library(ggplot2)
library(ggrough)
library(RSelenium)
library(htmlwidgets)

# make ggplot
count(mtcars, carb) %>%
  ggplot(aes(carb, n)) +
  geom_col() + 
  labs(title="Number of cars by carburator count") + 
  theme_grey(base_size = 16) -> gg_obj

# convert to rough chart
options <- list(
  Background=list(roughness=8),
  GeomCol=list(fill_style="zigzag", angle_noise=0.5, fill_weight=2))

rough_chart <- get_rough_chart(p = gg_obj, rough_user_options = options)

# save rough chart
saveWidget(rough_chart, "rough_chart.html")

# start selenium driver
rd <- remoteDriver(
  remoteServerAddr = "localhost", 
  port = 4444L,
  browserName = "chrome"
)

rd$open()

# navigate to saved rough chart file
rd$navigate(paste0("file:///", getwd(), "/rough_chart.html"))

# find canvas element and size
canvas_element <- rd$findElement("id", "canvas")
canvas_size <- canvas_element$getElementSize()

# zoom to chart size with padding
rd$setWindowSize(canvas_size$width + 2 * canvas_size$x, 
                 canvas_size$height + 2 * canvas_size$y)

# save as png
rd$screenshot(file = "rough_chart.png")

# close chrome
rd$close()

【讨论】:

    猜你喜欢
    • 2010-10-30
    • 2016-06-08
    • 2018-12-06
    • 1970-01-01
    • 2012-10-16
    • 1970-01-01
    • 2018-07-17
    相关资源
    最近更新 更多