1

I am trying to run this code in a Jupyter notebook

# 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))

After running this code I get the error NameError: name 'ggplot' is not defined

In fact, when I run %R require(ggplot2) I get an empty array: array([0], dtype=int32)

UPDATE

After @James comment, if I use %R ggplot(data=df) + geom_point(aes(x=A, y=B, color=C)) instead of ggplot(data=df) + geom_point(aes(x=A, y=B, color=C)) then I get Error in ggplot(data = df) : could not find function "ggplot"

This and this posts did not work for me

quant
  • 4,062
  • 5
  • 29
  • 70
  • 1
    Access to ggplot occurs in the R kernel. Try `%R ggplot(data=df) + geom_point(aes(x=A, y=B, color=C))` – James Apr 26 '19 at 12:04
  • @James I tried it, now I get `Error in ggplot(data = df) : could not find function "ggplot"`. I will update the question – quant Apr 26 '19 at 12:11
  • Have you tried `%R ggplot2::ggplot(data=df) + ggplot2::geom_point(aes(x=A, y=B, color=C))`, instead of loading the package ? – Jet Apr 26 '19 at 13:03
  • @Jet Yes, but I get `Error in ggplot(data = df) : could not find function "ggplot"` – quant Apr 26 '19 at 13:21

1 Answers1

0

I had the same problem.

The solution for me was to split the notebook up into different cells.

I assume you're running through https://www.datacamp.com/community/tutorials/tutorial-jupyter-notebook and the author doesn't explain where to split cells.

So you need to create a new cell for

%%R -i df

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

(Note the '%%' in front of R. I think it means it's cell magic and not line magic and cell magic has to happen at the very start of a cell.)

Here's what my notebook looks like:

Notebook

Alex
  • 66
  • 1
  • 4