# 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

This entry was posted in Python and tagged , , . Bookmark the permalink.
{"ft_lang_label":"__label__en","ft_lang_prob":0.76294684,"math_prob":0.6881602,"size":1109,"snap":"2023-14-2023-23","text_gpt3_token_len":286,"char_repetition_ratio":0.122171946,"word_repetition_ratio":0.035714287,"special_character_ratio":0.25067627,"punctuation_ratio":0.16444445,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.99013454,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2023-03-24T02:53:51Z\",\"WARC-Record-ID\":\"<urn:uuid:b50fc967-b3b0-4c62-8403-4a9c54b7d23a>\",\"Content-Length\":\"56712\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:4aa7197b-cb56-4e78-a8ee-0ccdfc515620>\",\"WARC-Concurrent-To\":\"<urn:uuid:77762ea2-2418-4ad5-b84b-2c4f1e4113ec>\",\"WARC-IP-Address\":\"213.186.33.19\",\"WARC-Target-URI\":\"http://thomas-cokelaer.info/blog/2012/04/how-to-call-r-plotting-function-from-python-using-rpy2/\",\"WARC-Payload-Digest\":\"sha1:T7IA4HSL2OKR5PSIMOPHOGAFYXPHCP2M\",\"WARC-Block-Digest\":\"sha1:4YPDLZGGY55SOWEIDBLPICPPMIOJNXIR\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2023/CC-MAIN-2023-14/CC-MAIN-2023-14_segments_1679296945242.64_warc_CC-MAIN-20230324020038-20230324050038-00352.warc.gz\"}"}