r - ipython notebook R cell magic作为python函数

标签 r ipython ipython-notebook rpy2

我有一些 %rmagic 可以接收数据框并绘制它。我不能用 python 中当前的 ggplot 实现来做到这一点。所以我想知道是否可以使用函数将数据帧传递给包含 R 代码的单元格并可能返回它。这是我的想法:

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


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

它不必是其他单元格的单元格,但我需要将某些内容传递给 R 并通过我可以重复使用的函数将其绘制在笔记本中。

最佳答案

我想最简单的方法是在 R 中定义一个函数它采用数据框并包含绘图逻辑。

必要的进口:

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

创建虚拟数据框:
df1 = pd.DataFrame({"A": [1, 2, 3], "B": [1, 2, 3]})
df2 = pd.DataFrame({"A": [3, 2, 1], "B": [1, 2, 3]})

编写绘图函数:
%%R
plot_gg <- function(df) {
    p <- ggplot(data=df) + geom_line(aes(x=A, y=B))
    print(p)
}

最后只用两行代码绘图:
for df in df1, df2:
    %Rpush df
    %R plot_gg(df)

关于r - ipython notebook R cell magic作为python函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27727833/

相关文章:

matplotlib - matplotlib 错误

python - 从自身内部以编程方式保存IPython笔记本吗?

r - 如何在 ggplot 命令中激活两个不同的 scale_fill_manual

css - R Shiny Table 折叠文本溢出

r - 使用函数在 R data.frame 中添加一列

R vs Pentaho Spoon 作为 ETL 工具

emacs - ipython emacs 缩进错误

python - Windows下Jupyter中的kernel-1234.json在哪里?

python - Jupyter 拒绝提供隐藏目录 (D :\) on windows

python - 运行 matplotlib 与 nbagg 交互的 linux VM 上的 ipython 笔记本