Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exporting PNG files from Plotly in R

Tags:

r

plotly

How can I export a Plotly chart as a image from R using code? (Not using the export button on the chart).

For example, this code from the Plotly site, create this chart:

library(plotly)
set.seed(100)
d <- diamonds[sample(nrow(diamonds), 1000), ]
plot_ly(d, x = carat, y = price, text = paste("Clarity: ", clarity),
        mode = "markers", color = carat, size = carat)

plotly chart

How can I save it as a image?

The official site has this material in python, but I didn't find something similar in R.

like image 439
Murta Avatar asked Nov 27 '15 14:11

Murta


People also ask

How do you save plots in plotly?

Save Your Plot Once you have your data and plot ready to go, click on SAVE on the left-hand side. Give your PLOT and DATA a filename and select the privacy setting.

Can plotly be used in R?

Plotly is a free and open-source graphing library for R. We recommend you read our Getting Started guide for the latest installation or upgrade instructions, then move on to our Plotly Fundamentals tutorials or dive straight in to some Basic Charts tutorials.


2 Answers

There is a export function which allows you to save images without the need to connect to plotly servers. You can find it in the plotly package doc:

p <- plot_ly(...)
export(p, file = "image.png")

You can even change the file type of output by selecting the extension as .png, jpeg or .pdf.

You can also save the image in html file which allows you the plotly experience like zooming or showing annotations by using htmlwidgets::saveWidget:

p <- plot_ly(...)
htmlwidgets::saveWidget(p, file = "image.html")
like image 74
JaKu Avatar answered Sep 29 '22 02:09

JaKu


In the Plotly docs in CRAN I discovered the function plotly_IMAGE.

Here is a example:

set.seed(100)
d <- diamonds[sample(nrow(diamonds), 1000), ]
p <- plot_ly(d, x = carat, y = price, text = paste("Clarity: ", clarity),
        mode = "markers", color = carat, size = carat)

plotly_IMAGE(p, width = 500, height = 500, format = "png", scale = 2,
             out_file = "~/desktop/test.png")

UPDATE

plotly_IMAGE works using Plotly server. A local solution is welcome.

like image 35
Murta Avatar answered Sep 29 '22 03:09

Murta