通过rpy2将ggplot2图形保存到Python bu中

2024-10-03 13:20:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将使用rpy2创建的ggplot2R对象的输出保存到Python控制的缓冲区中。在

我可以使用matplotlib来实现这一点,但我似乎无法通过rpy2使用ggplot2来实现。在


matplotlib.pyplot中,这可以通过以下方式实现:

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尝试:

^{pr2}$

错误:

NotImplementedError: Conversion 'py2ri' not defined for objects of type ''

我试图使用^{}功能。在


Tags: 对象ioimportnumpymatplotlibdefas方式
1条回答
网友
1楼 · 发布于 2024-10-03 13:20:44

R的ggplot2::ggsave需要一个字符串,指定路径(相对或绝对)作为参数filename的参数。例如"/this/is/my/figure.png"。在

Python BytesIO对象是完全不同的。它是一个内存中的二进制流(大致是Python对象,其行为类似于(二进制)文件)。在

如果使用ggsave不是绝对要求,请考虑使用 rpy2.robjects.lib.grdevices.render_to_bytesio()。这是一个在Jupyter笔记本中显示内联数字的函数:

from rpy2.ipython.ggplot import image_png
# pp is your ggplot2 figure
display(image_png(pp))

相关问题 更多 >