Exporting PNG files from Plotly in R - 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

Related

embedFonts is changing the bounding box of my R plot

I have made a beautiful plot in R to be used in a scientific journal. According to the journal's specifications, I need an eps file format with embedded fonts. Since R does not export eps files with embedded fonts, I am using the base graphics call embedFonts() to convert it. However, this call is changing the bounding box of my figure. In this simple example below, the white space is cropped. In my OCD-adjusted publication-quality plot, white space is added because I've already adjusted it perfectly to the edges.
I want the fonts to be embedded, but everything else to stay the same!
Here is an example:
setEPS()
postscript(file = "~/Desktop/test.eps", family = "Helvetica", colormodel = "srgb", width = 5, height = 3)
plot(x = 1:10, y = 1:10, col = "red", main = "Keep everything the same but embed my fonts!")
dev.off()
embedFonts(file = "/Users/athena/Desktop/test.eps", format = "eps2write", outfile = "/Users/athena/Desktop/stupid.eps")
So far I have:
- installed ghostscript using homebrew: $ brew install ghostscript
- learned that embedFonts needs FULL paths, no tilda's allowed
- specified the format as "eps2write" because the default "ps2write" changes it to a postscript
I spent so much effort on "reproducible research" with open data, open code, open journal, bla bla bla... I really don't want to have to make my final figures using illustrator conversion or something :(
The reason this happens is because embedFonts internally calls Ghostscript which in turn tries to act smart by fitting an "optimal" bounding box by trimming out some of the surrounding white space.
We can prevent that by drawing an invisible box around the perimeter of our 5inx3in drawing area in R. Just add one more line to your code snippet:
setEPS()
postscript(file = "~/Desktop/test.eps", family = "Helvetica", colormodel = "srgb", width = 5, height = 3)
plot(x = 1:10, y = 1:10, col = "red", main = "Keep everything the same but embed my fonts!")
box(which="outer", col="white")
dev.off()
embedFonts(file = "/Users/athena/Desktop/test.eps", format = "eps2write", outfile = "/Users/athena/Desktop/stupid.eps")
Another way to go about this is Jonathan's answer here which basically uses sed to read in Bounding Box info from the input file and writes it to the output file: http://r.789695.n4.nabble.com/eps-file-with-embedded-font-td903387.html as pointed out by #neilfws in a comment above.

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()

Export the graph generated by rCharts in shiny application

I want to be able to export the charts generated in my shiny application using rCharts to Image and PDF formats. Is there any provision in the rCharts library for that?
I have earlier used ggvis, It gives an option for resizing the chart in the browser and also an option to download the chart in HTML or PNG format. Anything similar to that?
Edit 1:
I'm using nvd3 and polyCharts as my charting libraries currently.
To download as image or pdf you can use a$exporting(enabled = T), assuming your chart is called a.
library(rCharts)
a <- hPlot(Pulse ~ Height, data = MASS::survey, type = "scatter", group = "Exer")
a$exporting(enabled = T)
a
To follow up on my comment above, I was a bit too quick to respond, as the htmlwidget::saveWidget() function is meant for widgets developed under the htmlwidgets.org framework. However, rCharts has a similar function:
library(rCharts)
a <- nPlot(Pulse ~ Height, data = MASS::survey, type = "scatterChart", group = "Exer")
a$save("demo.html", standalone=TRUE)
Where 'demo.html' is standalone html file. Creating a png is as simple as taking a screenshot. Note that you can also call this function in a shiny app.

Exporting PNG files from Plotly in R without internet

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.

R eps export and import into Word 2010

I'm having trouble with exporting eps files from R and importing into Word 2010.
I'm using ggplot2 plots, eg
library(ggplot2)
p <- qplot(disp,hp,data=mtcars) + stat_smooth()
p
Even after calling setEPS() neither of the following produce files which can be successfully imported.
ggsave("plot.eps")
postscript("plot.eps")
print(p)
dev.off()
The strange thing is that if I produce the plot using File -> Save As -> Postscript from the menu in the GUI, it can be imported correctly. However, when the Word document is subsequently exported as a pdf, the fonts in the graphic are a little jagged.
So my questions are:
What combination of (ggsave/postscript) settings allows me to produce eps files that can be imported into Word 2010?
How can I ensure the fonts remain clear when the Word document is exported as a pdf?
Update
After more investigation I have had more luck with cairo_ps to produce the plots. However, no text shows up when imported into Word.
Furthermore, after checking the various eps outputs (cairo_ps, save from the GUI, ggsave) in a latex document, it seems like the eps import filter in Word quite poor as the printed/pdf output doesn't match the quality of the latex'd document. The ggsave version (which uses postscript) did have some issues with colours that the other two methods didn't have though.
The conclusion is that this is a Word issue and therefore fortune(109) does not apply. I'd be happy to be proven otherwise, but I'll award the answer and the bounty to whoever can provide the commands that can replicate the output from the GUI in command form.
This worked for me... following advice in the postscript help page:
postscript("RPlot.eps", height = 4, width = 4, horizontal = FALSE, onefile = FALSE,
paper = "special")
library(ggplot2)
p <- qplot(disp,hp,data=mtcars) + stat_smooth()
p
#geom_smooth: method="auto" and size of largest group is <1000, so using loess. Use 'method = x' to #change the smoothing method.
#Warning message:
#In grid.Call.graphics(L_polygon, x$x, x$y, index) :
# semi-transparency is not supported on this device: reported only once per page
dev.off()
#quartz
# 2
The funny stuff at the end puts you on notice that this is only a Mac-tested solution, so far anyway.
Edit: I just tested it with R version 2.15.1 (2012-06-22) -- "Roasted Marshmallows": Platform: i386-pc-mingw32/i386 (32-bit) and MS Word 2007 in Win XP and it worked. Commands were Insert/Picture.../select eps format/select file.
Edit2: There is another method for saving besides directly using the postscript device. The savePlot method with an "eps" mode is available in Windows (but not in the Mac). I agree that the fonts are not as smooth as they appear on a Mac but I can discern no difference in quality between saving with savePlot and using save as from an interactive window.
savePlot(filename = "Rplot2", type = "eps", device = dev.cur(), restoreConsole = TRUE)
savePlot calls (.External(CsavePlot, device, filename, type, restoreConsole))
I solved the problem with exporting .eps files from R and importing into Word 2010 on Windows 7 using the colormodel="rgb" option (defaults to "srgb") of the postscript command.
postscript("RPlot.eps", height = 4, width = 4, horizontal = FALSE,
paper = "special", colormodel = "rgb")
library(ggplot2)
p <- qplot(disp,hp,data=mtcars) + stat_smooth(se=FALSE, method="loess")
p
dev.off()
You are probably better of using wmf as a format which you can create on Windows.
Word indeed doesn't support EPS very well.
A better solution is to export your graphs to Word or Powerpoint directly in native Office format. I just made a new package, export, that does exactly that, see
https://cran.r-project.org/web/packages/export/index.html and
for demo
https://github.com/tomwenseleers/export
Typical syntax is very easy, e.g.:
install.packages("export")
library(export)
library(ggplot2)
qplot(Sepal.Length, Petal.Length, data = iris, color = Species,
size = Petal.Width, alpha = I(0.7))
graph2doc(file="ggplot2_plot.docx", width=6, height=5)
graph2ppt(file="ggplot2_plot.pptx", width=6, height=5)
Output is vector format and so fully editable after you ungroup your graph in Word or Powerpoint. You can also use it to export statistical output of various R stats objects.
You can use R studio to knit html files with all of your plots and then open HTML files with Word.
knitr tutorial

Resources