0

I'm working on a web application that uses R enviroment with RApache. I have used the AJAX.updater function to send a couple of variables to an R-script an then this returns to the browser a ResponseText to display. There is no problem with that but now I wish to send a variable to an R-script that plots a graph, and then I want to return the image to the browser.

I'm able to display in the browser a plotted image by R with that script for example:

    <% setContentType("image/png")
t <- tempfile()

load(file="/var/www/oraculo/brew/ICER")

png(t, width=3.25, height=3.25, units="in", res=1200, pointsize=4)
plot(G,vertex.size=1,vertex.label=NA)
dev.off()
sendBin(**readBin**(t,'raw',n=file.info(t)$size))
unlink(t)


DONE
%>

And the other script that sends a variable and returns text strings:

new  Ajax.Updater( 'numFermin', '../brew/shortestPath.rhtml',
            {
                'method': 'GET', 
                'parameters': {'autini': autini, 'autfin':centro, 'XarXaj':                    red},
                'onSuccess': function(transport) {

                         txtRespuesta = transport.responseText;

                         if (txtRespuesta.lastIndexOf("Error")==-1){
                            var rutaMin = transport.**responseText**;
                            var accion = "";
                                    var url    = "index.src.php?accion=obtener&rutaMin="+rutaMin+"&numF=1";         
                            document.getElementById("oculto1").src=url;
                         }else{
                                                 ...

With GET variables of RApache I can work with 'autini' in the R-script.

One posible solution is to save the image in a file, but I don't like it very much. There is some way to put the bit stream readed in "readbin" into the "responseText", and then build a image in php? Wich function of AJAX I should use?

THANKS FOR YOUR TIME!

1 Answers1

0

I solved a similar problem with FastRWeb and Rserve installed on a server passing json formatted data like this in your html page using jquery.js. One important detail if using this solution is that if you try retrieving binary data with $.ajax you will need to copy jquery.js and fix 2 lines like explained in http://bugs.jquery.com/ticket/11461

  var myjsondata = '{ "entries": { "Labels": "MyTitle","Order": "1,2,3", "Class": "AM,PM,XF","Hwy": "29,29,31,20,29,26,29,29,24,44,29,26,29,32,49,29,23,24,44,41,29,26,28,29,39,29,28,29,26,26" } }';

   var request = $.ajax({         
        url: "http://Rserverip/cgi-bin/R/myboxplot",
        type: "POST",             
        xhrFields: {
              responseType : "arraybuffer"
        },
        contentType: "application/x-www-form-urlencoded; charset=UTF-8",
        dataType:  "binary",
        processData: false,
        crossDomain : true,
        data: myjsondata 
      });

    request.done(function(msg,ret_status,xhr) {
        var uInt8Array = new Uint8Array(msg);
            var i = uInt8Array.length;
            var binaryString = new Array(i);
            while (i--)
            {
              binaryString[i] = String.fromCharCode(uInt8Array[i]);
            }
            var data = binaryString.join('');
            var base64 = window.btoa(data);
            $(img).attr('src', "data:image/png;base64,"+base64 );
       });

On the server side, you will need a R program called myboxplot.R with (for example) the following code:

 run <- function(MyTable) {
 # read json into data frame
 mytmp <- fromJSON(rawToChar(.GlobalEnv$request.body))
 axes <- sapply(strsplit(json_data[['entries']][['Labels']], ",") , as.character)
 x <- sapply(strsplit(json_data[['entries']][['Class']], ",") , as.character)
 y <- sapply(strsplit(json_data[['entries']][['Hwy']], ",") , as.numeric )
 z <- sapply(strsplit(json_data[['entries']][['Order']], ",") , as.numeric ) 
 mydata <-  data.frame(x,y,z)
 mydata$count <- ave(as.numeric(mydata$x), mydata$x, FUN = length)
 #add the count to the x label
 mydata$x <- factor(do.call(paste, c(mydata[c("count", "x" )], sep = "]-")))
 mydata$x <- paste( "[",mydata$x, sep = "" ) 
 #reorder by z which is the order number
 mydata$reord <- reorder(mydata$x, mydata$z)
 p <- WebPlot(1191, 842)  # A3
 print( ggplot(mydata, aes(reord,y) ) + geom_boxplot (aes(fill=reord), alpha=.25, width=1, outlier.colour = "green") + labs(x = axes[1], y = axes[2]) + scale_fill_discrete(name=axes[3]) + stat_summary(aes(label=sprintf("%.02f",..y..)), fun.y=mean, geom="text", size=3) + theme_bw() + theme(axis.title.x = element_text(face="bold", colour="#990000", size=14, vjust = -1), axis.text.x  = element_text(angle=-90, hjust=1, size=12), plot.margin=unit(c(1,1,1.5,1),"lines"))  )
 p 
 } 

read the FastRweb doc for where to place this program and how to set up FastRWeb.

An easier solution which needs much less setting up on the server side is to use the R websockets package. Worked fine for me.

serf
  • 31
  • 2