| Hosted by CoCalc | Download
Kernel: Python 3 (system-wide)

RPy2 in Python 3 (Ubuntu Linux) kernel using ggplot2

%load_ext rpy2.ipython
/usr/local/lib/python3.6/dist-packages/rpy2/robjects/pandas2ri.py:14: FutureWarning: pandas.core.index is deprecated and will be removed in a future version. The public classes are available in the top-level namespace. from pandas.core.index import Index as PandasIndex
import rpy2.robjects as ro
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/local/lib/python3.6/dist-packages/rpy2/robjects/lib/ggplot2.py:72: UserWarning: This was designed againt ggplot2 version 3.2.1 but you have 3.3.0 'have %s' % (TARGET_VERSION, ggplot2.__version__))
datasets = importr('datasets') mtcars = data(datasets).fetch('mtcars')['mtcars']
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
15.000000 8.000000 301.000000 1.000000 5.000000 8.000000
21.400000 4.000000 121.000000 1.000000 4.000000 2.000000

Plotting via a temp file

# 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)
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")
R[write to console]: `geom_smooth()` using formula 'y ~ x'
Image in a Jupyter notebook
%%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)
R[write to console]: `geom_smooth()` using formula 'y ~ x'
Image in a Jupyter notebook