Exporting PNG files from Plotly in R without internet - r

In this question, Exporting PNG files from Plotly in R I asked how to export Plotly plots to disk.
I used the function plotly_IMAGE, but later discovered that the function uses the Plotly internet servers.
The question is, now that Plotly JavaScript is local, how can I create a png local file without internet?
I tried this code, without success:
library(plotly)
png(filename = "test.png")
plot_ly(x = 1:10)
dev.off()
The idea is to make it programaticaly, without click on export button over the chart.

They've added a new export function to the plotly package. But to my knowledge it does the same thing as #MLavoie's answer suggests. Usage:
p <- plot_ly(...)
export(p, file = "test.png")

You will to need install Phantom (http://phantomjs.org/download.html) which is quite easy and you can try this:
library(plotly)
library(webshot)
library(htmlwidgets)
m <- plot_ly(x = 1:10)
saveWidget(as.widget(m), "temp.html")
webshot("temp.html", file = "test.png",
cliprect = "viewport")
you will find temp.html and temp.png in your working directory.

Related

RStudio : what is the code behind the export>save as image button?

I try to find a way to save a plotly graph as png without installing orca (I'm not allowed to).
It appears that if I plot my graphics, lets say :
library(dplyr)
library(plotly)
p <- plot_ly(z = ~volcano) %>% add_surface()
p
and then clic on export>save as image>Save as png, the resulting static plot is available on my computer
But If I try to use classical png() like this :
png("myvolcano.png")
plot_ly(z = ~volcano) %>% add_surface()
dev.off()
I get a blank png...
(while it's working for a classical plot(1) )
How to reproduce by code what I get from the menu bar ?
Thank you!
Hi this is more a comment than an answer but my reputation does not allow me to comment.
You can use 2 strategies to export plotly graphs:
use orca() function in the plotly pkg (if you ?orca will find all the explanations)
use htmlwidgets::saveWidget(p, file = "myvolcano.html") which downloads in html format
In the past there was a function export() but it is deprecated now.
Hope this helps.

Saving plot.ly image to RData file

I create a plot_ly image using:
MilesPlotly <- plot_ly(x = TripDetails$TotalDistanceMiles, type = "histogram")
I then want to save it to an RData file to simply open it later (hence pre-compute)
save(MilesPlotly, file = "my/path/here/myPlot.RData")
Later on I want to simply plot it by doing
load(my/path/here/myPlot.RData)
MilesPlotly
Now, this works on Mac. This does not work on my Ubuntu server on AWS.
Does anyone have any ideas why the discrepancy? The plotly version on both is 3.6.0.
Your code doesn't work on my windows environment and plotly_build() solves it (I'm not sure this code works on your env).
MilesPlotly <- plot_ly(x = TripDetails$TotalDistanceMiles, type = "histogram")
MilesPlotly <- plotly_build(MilesPlotly)
save(MilesPlotly, file = "my/path/here/myPlot.RData")
load("my/path/here/myPlot.RData")
MilesPlotly
After some tweaking, I realized I needed to do two things:
1) I updated R to 3.3.1
2) You need to "build" the plot before saving it. That means:
MilesPlotly <- plot_ly(x = TripDetails$TotalDistanceMiles, type = "histogram") %>%
build()

Exporting PNG files from Plotly in R

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)
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.
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")
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.
Since I am new, I'm unable to comment so I am posting this as a response. The export function is deprecated as of plotly v4.9.0. Instead, the orca function is the suggested method to export plotly objects as static images. Learn more here: orca function R documentation
According to plotly the following should work :
1) Install Orca as described here : https://github.com/plotly/orca
2) You might need to restart your PC
Then run the following code :
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(...)
orca(p, file = "image.png")
Note : I found giving full path is raising a javascript error. So I just gave filename. The files are being saved in "C:/Users/user/Documents" in Windows.
I wanted to warn other users, that orca changes text when saved.
from my terminal, I have:
I specified Corbal (Body) in my plot.
When I saved using orca(z,width = 8*96, height = 3*96, save_path), I got
when I saved using export(z, file = save_path ), I got:
You can tell that the font family is different. Very annoying

Create a gif from a series of Leaflet maps in R

I am looking for an automated method to convert leaflet R Studio plots into image files.
Seems like exporting a leaflet widget to HTML is straightforward (Saving leaflet output as html). However I cannot find any answers or docs about how to save the image produced by a leaflet widget as an image. It seems strange that I can do this manually in R Studio but that there isn't some function within R Studio that can be called to do the same thing.
I've tried the usual suspects, variations on the following:
png("test_png.png")
map
dev.off()
But these all just print white or print a file that can't even be opened. IF I understand this Git discussion correctly, seems like something in leaflet is not available but is desired by users.
In the meantime, R Studio clearly has a way to render this image into an image file, making me press a button to do it. Is there a way to automate this? How can I export the images plotted in R Studio to image files? I need image files and I need this to be programmatic because I want to make a gif out of a few hundred maps.
Alternately, I'd welcome suggestions for a workaround. I might try this: Python - render HTML content to GIF image but if someone has alternatibve suggestions, please share.
I've been trying to do this with a combination of the webshot package and saveWidget from htmltools, although it's pretty slow. For a few hundred maps, it's probably not too bad if you're only doing it here and there. But, for real-time application it is too slow.
There are two external applications you need for this workflow. webshot takes screenshots of webpages and requires you to install PhantomJS first (it's tiny and easy). I also use ImageMagick (and needs to be accessible from the command line) to create the .gif files, but I'm sure there many other programs you could use to make gifs.
The idea is just to create the maps in a loop, save them to a temporary html file with saveWidget and use webshot to turn it into a png (slow). Then, once you have all the pngs, use ImageMagick to convert them to a gif (fast).
Here is an example, I also load ggmap, but only to get a location to zoom in on.
library(webshot)
library(leaflet)
library(htmlwidgets)
library(ggmap)
loc <- geocode('mt everest') # zoom in everest
zooms <- seq(2,14,3) # some zoom levels to animate
## Make the maps, this will make some pngs called 'Rplot%02d.png'
## in your current directory
for (i in seq_along(zooms)) {
m <- leaflet(data=loc) %>%
addProviderTiles('Esri.WorldImagery') %>%
setView(lng=loc$lon, lat=loc$lat, zoom=zooms[i])
if (i==1)
m <- m %>% addPopups(popup="Going to see Mt Everest")
if (i==length(zooms))
m <- m %>%
addCircleMarkers(radius=90, opacity = 0.5) %>%
addPopups(popup = 'Mt Everest')
## This is the png creation part
saveWidget(m, 'temp.html', selfcontained = FALSE)
webshot('temp.html', file=sprintf('Rplot%02d.png', i),
cliprect = 'viewport')
}
Then, it is just converting pngs to gif. I did this on a Windows, so command might be slightly different on a mac/linux (I think just single quotes instead of double quotes or something). These commands are from a command line/shell, but you could also use system/system2 to call from R or try the animation package that has some wrapper functions for ImageMagick. To make a simle gif with nothing fancy is simply, convert *.png animation.gif. I used a slightly longer code to make the pngs smaller/add some delays/and have the sequence go in and out.
convert Rplot%02d.png[1-5] -duplicate 1,-2-1, -resize "%50" gif:- | convert - -set delay "%[fx:(t==0||t==4)?240:40]" -quiet -layers OptimizePlus -loop 0 cycle.gif
You can create a series of PNG files as answered by jenesaisquoi (first answer). Then create gif with the png files using the below code with magick package.
library(magick)
png.files <- sprintf("Rplot%02d.png", 1:20) #Mention the number of files to read
GIF.convert <- function(x, output = "animation.gif")#Create a function to read, animate and convert the files to gif
{
image_read(x) %>%
image_animate(fps = 1) %>%
image_write(output)
}
GIF.convert(png.files)
You don't require to install ImageMagick software on PC.
Code Link: Animation.R
I have table with 3 columns: lat,lon,day (376 days).
The process is: create the map -> save the map as HTML -> save the map as PNG -> import the pic -> plot it (with plot + ggimage)
All this process, will be in a loop
library(leaflet)
library(animation)
library(png)
library(htmlwidgets)
library(webshot)
library(ggmap)
saveGIF({
for (i in 1:376) {
map = leaflet() %>%
addTiles() %>%
setView(lng = lon_lat[1,2], lat = lon_lat[1,1], zoom = 5)%>%
addMarkers(lng = lon_lat[lon_lat$day == i,2],lat = lon_lat[lon_lat$day == i,1])
saveWidget(map, 'temp.html', selfcontained = FALSE) ## save the html
webshot('temp.html', file=sprintf('Rplot%02d.png', 1),cliprect = 'viewport') ## save as png
img = readPNG("Rplot01.png") ### read the png
plot(ggimage(img)) ###reading png file
}
})

save image of d3heatmap in a file

I am using d3heatmap package in R for to draw heatmaps. When I use it in Rstudio, I can save images that it produces by choosing save image from the viewer menu. I am wondering how I can save the heatmap to a file in an Rscript. Apparently, png(filename) does not work.
A potential approach is using htmlwidgets and save it in html form only since the d3heatmap returns object of class "d3heatmap" "htmlwidget"
EG.
library(htmlwidgets)
data(mtcars)
map <- d3heatmap(mtcars, scale = "column")
saveWidget(map, "test.html")

Resources