R and Python in one Jupyter notebook

Yes, it is possible! Use rpy2.

You can install rpy2 with: pip install rpy2

Then run %load_ext rpy2.ipython in one of your cells. (You only have to run this once.)

Now you can do the following:

Python cell:

# enables the %%R magic, not necessary if you've already done this
%load_ext rpy2.ipython

import pandas as pd
df = pd.DataFrame({
    'cups_of_coffee': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
    'productivity': [2, 5, 6, 8, 9, 8, 0, 1, 0, -1]
})

R cell:

%%R -i df -w 5 -h 5 --units in -r 200
# import df from global environment
# make default figure size 5 by 5 inches with 200 dpi resolution

install.packages("ggplot2", repos="http://cran.us.r-project.org", quiet=TRUE)
library(ggplot2)
ggplot(df, aes(x=cups_of_coffee, y=productivity)) + geom_line()

And you’ll get your pretty figure plotting data from a python Pandas DataFrame.

Leave a Comment