J'essaie de sauvegarder la sortie d'un ggplot2
R objet créé en utilisant rpy2
dans un tampon contrôlé par Python.
Je suis capable de faire cela en utilisant matplotlib
mais je ne peux pas semble le faire avec ggplot2 via rpy2
.
Dans matplotlib.pyplot
, cela peut être accompli avec:
import matplotlib.pyplot as plt
import io
import numpy
def test_save():
x = numpy.linspace(-5, 5)
y = 3*x + 2
fig = plt.figure()
plt.plot(x, f)
buf = io.BytesIO()
plt.savefig(buf, format = "png")
return buf
ggplot2
tentative:
import io
import numpy
import rpy2.robjects as robjects
from pandas import DataFrame
import rpy2.robjects.lib.ggplot2 as ggplot2
def test_ggplot2_save():
x = numpy.linspace(-5, 5)
y = 3*x + 2
df = DataFrame({"x": x, "y": y})
gp = ggplot2.ggplot(df)
pp = (gp
+ ggplot2.aes_string(x="x", y="y")
+ ggplot2.geom_point()
+ ggplot2.labs(title="MY DATA", x="x", y="y"))
# pp.plot()
buf = io.BytesIO()
robjects.r.ggsave(filename=buf, plot=pp, width=200, height=120, unit="mm")
Erreur:
NotImplementedError: La conversion "py2ri" n'est pas définie pour les objets de type ""
J'essayais d'utiliser le rpy2.robjects.lib.ggplot2.GGPlot.save
fonctionnalité.
Réponses:
1 pour la réponse № 1R "s ggplot2::ggsave
attend une chaîne spécifiant un chemin (relatif ou absolu) comme argument du paramètre filename
. Par exemple "/this/is/my/figure.png"
.
Un python BytesIO
l'objet est assez différent. C'est un flux binaire en mémoire (en gros un objet Python qui se comporte comme un fichier (binaire)).
Si vous utilisez ggsave
n'est pas une exigence absolue, envisagez d'utiliser
rpy2.robjects.lib.grdevices.render_to_bytesio()
. C’est la fonction qui permet d’afficher les figures suivantes dans le bloc-notes Jupyter:
from rpy2.ipython.ggplot import image_png
# pp is your ggplot2 figure
display(image_png(pp))