在Jupyter笔记本中内联显示R ggplots

5

我正在尝试运行这里找到的一个简单示例: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一样在笔记本中内联显示它? 注意:我使用命令conda install -c r r-essentials(通常包括ggplot?)在Jupyter中安装了R,如上述链接所述。 非常感谢你的帮助。
1个回答

5

好的,我现在试了一下... 对我而言,这个方法行得通:

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

你需要添加一个print()语句。不知道为什么。


1
谢谢,它有效。我想知道为什么这里需要它,找出原因会很好。 - user7188934

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接