【问题标题】:Cannot use ggplot2 in python jupyter notebook无法在 python jupyter notebook 中使用 ggplot2
【发布时间】:2019-09-15 22:11:56
【问题描述】:

我正在尝试在 Jupyter 笔记本中运行此代码

# Hide warnings if there are any
import warnings
warnings.filterwarnings('ignore')

# Load in the r magic
%load_ext rpy2.ipython

# We need ggplot2
%R require(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: name 'ggplot' is not defined

事实上,当我运行%R require(ggplot2) 时,我得到一个空数组:array([0], dtype=int32)

更新

@James 评论后,如果我使用%R ggplot(data=df) + geom_point(aes(x=A, y=B, color=C)) 而不是ggplot(data=df) + geom_point(aes(x=A, y=B, color=C)),那么我会得到Error in ggplot(data = df) : could not find function "ggplot"

Thisthis 帖子对我不起作用

【问题讨论】:

  • 对 ggplot 的访问发生在 R 内核中。试试%R ggplot(data=df) + geom_point(aes(x=A, y=B, color=C))
  • @James 我试过了,现在我得到了Error in ggplot(data = df) : could not find function "ggplot"。我会更新问题
  • 你试过%R ggplot2::ggplot(data=df) + ggplot2::geom_point(aes(x=A, y=B, color=C)),而不是加载包吗?
  • @Jet 是的,但我得到了Error in ggplot(data = df) : could not find function "ggplot"

标签: python r ggplot2 jupyter-notebook


【解决方案1】:

我遇到了同样的问题。

我的解决方案是将笔记本分成不同的单元格。

我假设您正在运行https://www.datacamp.com/community/tutorials/tutorial-jupyter-notebook,而作者没有解释在哪里拆分单元格。

所以你需要为

创建一个新单元格
%%R -i df

# Plot the DataFrame df
ggplot(data=df) + geom_point(aes(x=A, y=B, color=C))

(注意 R 前面的 '%%'。我认为这意味着它是细胞魔法而不是线条魔法,细胞魔法必须在细胞的一开始就发生。)

这是我的笔记本的样子:

Notebook

【讨论】:

    猜你喜欢
    • 2020-10-12
    • 2020-03-26
    • 2021-07-08
    • 1970-01-01
    • 2021-11-08
    • 1970-01-01
    • 2018-02-18
    • 1970-01-01
    • 2021-07-25
    相关资源
    最近更新 更多