You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将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:

  1. 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 image
    
  2. Modify 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:

  • ggrough builds 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:30:34