如何将ggrough绘制的图表保存为.png格式?
Saving ggrough Charts as PNG Files
The issue here is that ggrough generates an htmlwidget object, not a traditional ggplot2 graphic compatible with base R's plotting devices like png()/dev.off(). So we need to use tools built for saving htmlwidgets, then convert the output to PNG.
Here's the step-by-step solution:
First, install the required packages (if you haven't already):
install.packages(c("htmlwidgets", "webshot")) webshot::install_phantomjs() # Required for webshot to render HTML to imageModify your code to save the rough chart properly:
library(ggplot2) library(ggrough) library(htmlwidgets) library(webshot) # Your original chart code 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) ) # Generate the rough chart widget rough_chart <- get_rough_chart(p, options) # Save the widget as an HTML file first saveWidget(rough_chart, "temp_rough_chart.html") # Convert the HTML file to PNG (adjust width/height to match your chart needs) webshot("temp_rough_chart.html", "ggrough.png", vwidth = 800, vheight = 600) # Optional: Clean up the temporary HTML file file.remove("temp_rough_chart.html")
Why this works:
ggroughbuilds on htmlwidgets to create its hand-drawn style charts, which are rendered as interactive HTML under the hood. Base R's graphic devices can't capture this output directly.saveWidget()exports the htmlwidget to a static HTML file.webshot()uses a headless browser (PhantomJS) to render the HTML and save it as a PNG image.
Alternative (using webshot2):
If you prefer a more modern alternative, you can use webshot2 instead of webshot (it uses Chrome/Chromium instead of PhantomJS):
install.packages("webshot2") library(webshot2) # After generating rough_chart saveWidget(rough_chart, "temp_rough_chart.html") webshot("temp_rough_chart.html", "ggrough.png", vwidth = 800, vheight = 600) file.remove("temp_rough_chart.html")
内容的提问来源于stack exchange,提问作者bill999
相关产品推荐
相关产品推荐

