Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ipython notebook R cell magic as a python function

I have some %rmagic that takes in a dataframe and plots it. I can't do this with the current ggplot implementation in python. So I was wondering if I could use a function to pass the dataframe to a cell that contains R code and possibly return it. Here is what I had in mind:

 #cell 1
 def plot_in_r(dataframe):
     pass_to_cell_2(dataframe)


 #cell 2
 %%R -i dataframe 
 ggplot(dataframe) + geom_bar()

It doesn't have to be a cell to other cell, but I need to pass something to R and have it plot inside the notebook through a function that I can use repeatedly.

like image 716
jwillis0720 Avatar asked Dec 25 '22 00:12

jwillis0720


1 Answers

I guess the simplest way to do that is to define a function in R which takes a data frame and contains the plotting logic.

necessariy imports:

import rpy2
import pandas as pd
%load_ext rpy2.ipython
%R require("ggplot2")

creating dummy data frames:

df1 = pd.DataFrame({"A": [1, 2, 3], "B": [1, 2, 3]})
df2 = pd.DataFrame({"A": [3, 2, 1], "B": [1, 2, 3]})

writing the plotting function:

%%R
plot_gg <- function(df) {
    p <- ggplot(data=df) + geom_line(aes(x=A, y=B))
    print(p)
}

and finally plot with only two lines of code:

for df in df1, df2:
    %Rpush df
    %R plot_gg(df)
like image 155
cel Avatar answered Dec 28 '22 07:12

cel