Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download

rpy2 in python3

816 views
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

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