python - 在 jupyter 笔记本中内联显示 R ggplots

标签 python r ggplot2 jupyter-notebook

我正在尝试运行此处找到的一个简单示例:https://www.datacamp.com/community/blog/jupyter-notebook-r#gs.OczVCjA

import warnings
warnings.filterwarnings('ignore')
# Load in the r magic

import rpy2.ipython

%reload_ext rpy2.ipython

# We need ggplot2

%R require(ggplot2)
%R library("ggplot2")
# Load in the pandas library
import pandas as pd 
# Make a pandas DataFrame
df = pd.DataFrame({'Alphabet': ['a', 'b', 'c', 'd','e', 'f', 'g', 'h','i'],
                   'A': [4, 3, 5, 2, 1, 7, 7, 5, 9],
                   'B': [0, 4, 3, 6, 7, 10,11, 9, 13],
                   'C': [1, 2, 3, 1, 2, 3, 1, 2, 3]})
# Take the name of input variable df and assign it to an R variable of the same name
%R -i df
# Plot the DataFrame df
ggplot(data=df) + geom_point(aes(x=A, y=B, color=C))

起初我有一个 NameError “ggplot node defined”

然后我将 %R 添加到最后一行,现在获得以下输出:

R object with classes: ('gg', 'ggplot') mapped to:
<ListVector - Python:0x7fc6a73c1d88 / R:0x3c4e768>
[DataF..., ListV..., Envir..., ..., Envir..., Envir..., ListV...]
R object with classes: ('gg', 'ggplot') mapped to:
<ListVector - Python:0x7fc6a73c1d88 / R:0x3c4e768>
[DataF..., ListV..., Envir..., ..., Envir..., Envir..., ListV...]
R object with classes: ('gg', 'ggplot') mapped to:
<ListVector - Python:0x7fc6a73c1d88 / R:0x3c4e768>
[DataF..., ListV..., Envir..., ..., Envir..., Envir..., ListV...]
  scales: <class 'rpy2.robjects.environments.Environment'>
  R object with classes: ('ScalesList', 'ggproto') mapped to:
<Environment - Python:0x7fc6a7682808 / R:0x215a968>
  ...
  data: <class 'rpy2.robjects.environments.Environment'>
  R object with classes: ('FacetNull', 'Facet', 'ggproto') mapped to:
<Environment - Python:0x7fc6a76829c8 / R:0x281c138>
  layers: <class 'rpy2.robjects.environments.Environment'>
  R object with classes: ('environment',) mapped to:
<Environment - Python:0x7fc6a7682548 / R:0x1544d58>
R object with classes: ('gg', 'ggplot') mapped to:
<ListVector - Python:0x7fc6a73c1d88 / R:0x3c4e768>
[DataF..., ListV..., Envir..., ..., Envir..., Envir..., ListV...]

是否创建了绘图以及如何像使用 matplotlib 那样在笔记本中内联显示它?

n.b.:我使用命令 conda install -c r r-essentials(通常包括 ggplot?)在 Jupyter 中安装了 R,如上面的链接所述

非常感谢您

最佳答案

好的,我已经试过了... 这对我有用:

%R print(ggplot(data=df) + geom_point(aes(x=A, y=B, color=C)))

您必须添加一个print() 语句。不知道为什么。

关于python - 在 jupyter 笔记本中内联显示 R ggplots,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43975244/

相关文章:

python - ubuntu上python导入sidekit出错

r - 在 Fedora Linux 中最近更新的 R 中安装 Quantstrat

r - 使用 R plotly 中的标记将抖动添加到分组箱线图

r - 使用 facet_grid 时在 ggplot2 中指定自定义误差线

R ggplot2 在图例名称中使用变量表达式

r - geom_text()、plotmath 和 %

python - 为什么要对单词进行标记/预处理以进行语言分析?

python - TF 2.0 顺序 CNN 转换为 LSTM 进行回归 "Negative dimension size"错误

python - 就地更新 ctypes 指针

使用线性内核调整 SVM 时,R 插入符号异常缓慢