The answer provided by @Peter Gaultney produced an error for my box plot.
These two methods might work in more circumstances and improve the image quality using htmlwidgets::onRender().
Option 1. As @chinsoon12 suggests, save as SVG. This code will open a web browser then make the browser download the image. Note that setting the viewer to null will stop the RStudio viewer pane from working, so you'll need to save it, save the plot image, and then restore it.
library(htmlwidgets)
# Save viewer settings (e.g. RStudio viewer pane)
op <- options()
# Set viewer to web browser
options(viewer = NULL)
# Use web browser to save image
p %>% htmlwidgets::onRender(
"function(el, x) {
var gd = document.getElementById(el.id);
Plotly.downloadImage(gd, {format: 'svg', width: 600, height: 800, filename: 'plot'});
}"
)
# Restore viewer to old setting (e.g. RStudio)
options(viewer = op$viewer)
Option 2. You can save as PNG and specify a higher resolution. You should probably increase the line thickness, fonts, etc. for this method.
library(htmlwidgets)
# Save viewer settings (e.g. RStudio viewer pane)
op <- options()
# Set viewer to web browser
options(viewer = NULL)
# Use web browser to save image
p %>% htmlwidgets::onRender(
"function(el, x) {
var gd = document.getElementById(el.id);
Plotly.downloadImage(gd, {format: 'png', width: 1200, height: 1600, filename: 'plot'});
}"
)
# Restore viewer to old setting (e.g. RStudio)
options(viewer = op$viewer)