CoCalc Public Filesrpy2-tidyverse.ipynbOpen with one click!
Author: Harald Schilly
Views : 210
Description: rpy2 in python3
Compute Environment: Ubuntu 18.04 (Deprecated)

RPy2 in Python 3 (Ubuntu Linux) kernel using ggplot2

In [1]:
%load_ext rpy2.ipython
In [2]:
import rpy2.robjects as ro
In [3]:
import math, datetime import rpy2.robjects.lib.ggplot2 as ggplot2 import rpy2.robjects as ro from rpy2.robjects.packages import importr, data base = importr('base')
/usr/lib/python3/dist-packages/rpy2/robjects/lib/ggplot2.py:67: UserWarning: This was designed againt ggplot2 version 2.2.1 but you have 3.1.0 warnings.warn('This was designed againt ggplot2 version %s but you have %s' % (TARGET_VERSION, ggplot2.__version__))
In [4]:
datasets = importr('datasets') mtcars = data(datasets).fetch('mtcars')['mtcars']
In [5]:
mtcars
R/rpy2 DataFrame (32 x 11)
mpg cyl disp ... am gear carb
21.000000 6.000000 160.000000 ... 1.000000 4.000000 4.000000
21.000000 6.000000 160.000000 ... 1.000000 4.000000 4.000000
22.800000 4.000000 108.000000 ... 1.000000 4.000000 1.000000
21.400000 6.000000 258.000000 ... 0.000000 3.000000 1.000000
... ... ... ... ... ... ...
15.800000 8.000000 351.000000 ... 1.000000 5.000000 4.000000
19.700000 6.000000 145.000000 ... 1.000000 5.000000 6.000000

Plotting via a temp file

In [6]:
# credits: https://stackoverflow.com/questions/15060838/using-rpy2-with-ipython-notebooks import uuid from rpy2.robjects.packages import importr from IPython.core.display import Image grdevices = importr('grDevices') def ggplot_notebook(gg, width = 800, height = 600, name = None): fn = name or '{uuid}.png'.format(uuid = uuid.uuid4()) grdevices.png(fn, width = width, height = height) gg.plot() grdevices.dev_off() return Image(filename=fn)
In [7]:
pp = ggplot2.ggplot(mtcars) + \ ggplot2.aes_string(x='wt', y='mpg', col='factor(cyl)') + \ ggplot2.geom_point() + \ ggplot2.geom_smooth(ggplot2.aes_string(group = 'cyl'), method = 'lm') ggplot_notebook(pp, name = "rpy2_cars.png")
In [8]:
%%R -i mtcars -w 7 -h 4 --units in -r 120 require(ggplot2) pp = ggplot(mtcars) + aes_string(x='wt', y='mpg', col='factor(cyl)') + geom_point() + geom_smooth(aes_string(group = 'cyl'), method = 'lm') plot(pp)
/usr/lib/python3/dist-packages/rpy2/robjects/pandas2ri.py:196: FutureWarning: from_items is deprecated. Please use DataFrame.from_dict(dict(items), ...) instead. DataFrame.from_dict(OrderedDict(items)) may be used to preserve the key order. res = PandasDataFrame.from_items(items)
In [ ]: