R inside of IPython Part 1

Now IPython notebook is nice, but what if I prefer ggplot2. First try matplotlib, it is really nice. But if you still want to use ggplot2 than you can access R from python using the rpy2 module demonstrated here.


In [1]:
# Imports
import numpy as np
import scipy as sp
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline

In [3]:
# Load R magic
%load_ext rmagic


/usr/local/lib/python2.7/dist-packages/IPython/extensions/rmagic.py:693: UserWarning: The rmagic extension in IPython is deprecated in favour of rpy2.ipython. If available, that will be loaded instead.
http://rpy.sourceforge.net/
  warnings.warn("The rmagic extension in IPython is deprecated in favour of "

In [11]:
# Make data to plot in python
x = np.random.uniform(0, 1000, size=1000)
y = np.random.normal(1000, size=1000)

In [42]:
# Plot using matplotlib
plt.scatter(x=x, y=y, color='k')
plt.xlabel('X', fontsize=14)
plt.ylabel('Y', fontsize=14)
plt.grid()


Here is a simple plot using R. First we push our x and y arrays over to R and then plot them.


In [14]:
%Rpush x y
%R plot(x, y)


A little more complicated plot can be done using the R cell magic command %%R. Here everything in the cell is called with R.


In [29]:
%%R -i x,y
library(ggplot2)
dat = data.frame(x=x, y=y)
ggplot(dat, aes(x=x, y=y)) + geom_point()


See this IPython notebook for more information about R magic.


In [ ]: