Save R plot as a BLOB

July 30, 2010

(This article was first published on stotastic » R, and kindly contributed to R-bloggers)

I recently posed a question on stackoverflow on whether anyone knew an efficient way to save an R plot to a MySQL database as a BLOB. My plan was to use my personal desktop to perform R routines and save them to a web server, where they could then be accessed and displayed on a web page using a little PHP magic. After getting numerous responses on what a terrible idea this was, I was able to piece my own solution together. The steps are fairly simple. First, save the plot as a temp file, Second, read it back into R as a binary string. Third, insert the binary text into the database using the RODBC library. The code snippet is below.

## open connection
channel <- odbcConnect("")
## create a plot
x <- rnorm(100,0,1)
## save plot as temp file
png(filename="temp.png", width=500, height=500)
hist(x, col="light blue")
## read temp file as a binary string
plot_binary <- paste(readBin("temp.png", what="raw", n=1e6), collapse="")
## insert binary sting into a table
sqlQuery(channel, paste("INSERT INTO test VALUES (1, x'",plot_binary,"')", sep=""))
## close connection

I understand the ‘other way’ to do this (and most would argue better) would be to ftp the file to the server and save only the file path to the database. I guess I’m just being a bit lazy by letting the database do all the storage details, but so far so good.

To leave a comment for the author, please follow the link and comment on their blog: stotastic » R. offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Tags: , ,

Comments are closed.

Search R-bloggers


Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)