How to call R plotting function from python using rpy2

Python has already very good librairies from plotting (e.g., matplotlib, mayavi), however, it is sometimes useful to use some of the plotting functionalities offered by R. Thanks to the rp2 package, it is quite easy. Let us try to use the simple function plot and hist. We will use numpy to create the randon data to plot but you could use simple python

# import rpy2 robjects to call R code
import rpy2.robjects as robjects
 
# some aliases to R functions
rplot = robjects.r('plot')
rhist = robjects.r('hist')
 
# some random data. Could use numpy instead
data = [random.randint(0,10) for x in range(0,1000)]
 
# calling rplot 
robjects.r('dev.new()') # optional: create a new figure
rplot(robjects.FloatVector(data[:]), ylab="") 
 
 
# now, the histogram
robjects.r('dev.new()') # optional: create a new figure
rhist(robjects.FloatVector(data[:]), xlab="", main="user title")

The code is quite straightforward, however, note that you must use the ylab argument in rplot otherwise the ylabel is replaced by the data contents.

similarly, in the rhist, you must set xlab and the title using main

Please follow and like us:
This entry was posted in Python and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *