0

Being a R user, I am learning to incorporate python command in R through reticulate, I tried plotting graph using the plotnine package in R but it returned the following error, can anyone help?

library(reticulate)
library(ggplot2)

pd <- import('pandas', as='pd',convert=FALSE)
p9 <- import('plotnine')

mpg_py <- r_to_py(mpg,convert=FALSE)
mpg_pd <- pd$DataFrame(data=mpg_py)

p9$ggplot(data=mpg_pd,p9$aes(x='displ',y='cty'))

# Error in py_call_impl(callable, dots$args, dots$keywords) : 
#   AttributeError: 'NoneType' object has no attribute 'f_locals'
lokheart
  • 23,743
  • 39
  • 98
  • 169

1 Answers1

0

The answer to this question pointed me down a promising path for this error. It seems the error is due to an issue in the patsy package that handles the namespace/scoping for plotnine. By default the plotnine.ggplot constructor creates an environment to know where to get the plotting data and aesthetics. So adapting from the linked answer, here's a potential solution where we import the patsy package and use the environment parameter in the ggplot function to pass an evaluation environment (docs).

library(reticulate)
library(ggplot2)


pd = import('pandas',convert=F)
p9 = import('plotnine')
# new imports
patsy = import('patsy')
  # import to be able to show in RStudio (see issue here: https://github.com/rstudio/rstudio/issues/4978)
matplotlib = import('matplotlib')
matplotlib$use('tkAgg')
plt = import('matplotlib.pyplot')

mpg_py <- r_to_py(mpg,convert=FALSE)
mpg_pd <- pd$DataFrame(data=mpg_py)

plot_py = p9$ggplot(mpg_pd,p9$aes(x='displ',y='cty'),
                    # new code (-1 was the only value that didn't throw an error)
          environment = patsy$EvalEnvironment$capture(eval_env=as.integer(-1)))
print(class(plot_py)) # "plotnine.ggplot.ggplot" "python.builtin.object"

# Actually show the plot
plot_py
plt$show()
cookesd
  • 1,296
  • 1
  • 5
  • 6