【问题标题】:Rpy2 & ggplot2: LookupError 'print.ggplot'Rpy2 & ggplot2: LookupError 'print.ggplot'
【发布时间】:2012-03-21 08:53:39
【问题描述】:

不受任何预先存在的 R、Rpy2 和 ggplot2 知识的阻碍,我永远不会更喜欢从 Python 创建一个简单表的散点图。

我刚刚安装了这个设置:

  • Ubuntu 11.10 64 位
  • R version 2.14.2(来自 r-cran 镜像)
  • ggplot2(通过R> install.packages('ggplot2')
  • rpy2-2.2.5(通过easy_install

在此之后,我可以使用 ggplot2 从交互式 R 会话中绘制一些示例数据帧。

但是,当我只是尝试导入 ggplot2 时,正如我在网上找到的示例中看到的那样,我收到以下错误:

from rpy2.robjects.lib import ggplot2
  File ".../rpy2/robjects/lib/ggplot2.py", line 23, in <module>
    class GGPlot(robjects.RObject):
  File ".../rpy2/robjects/lib/ggplot2.py", line 26, in GGPlot
    _rprint = ggplot2_env['print.ggplot']
  File ".../rpy2/robjects/environments.py", line 14, in __getitem__
    res = super(Environment, self).__getitem__(item)
LookupError: 'print.ggplot' not found

谁能告诉我我做错了什么?正如我所说,有问题的导入来自一个在线示例,所以很可能还有其他方法我应该通过 rpy2 使用 gplot2。


作为参考,与上述问题无关,这是我想绘制的数据框示例,一旦我开始导入工作(查看示例应该不是问题)。这个想法是创建一个散点图,其中 x 轴上的长度、Y 轴上的百分比和布尔值用于为点着色,然后我想将其保存到文件(图像或 pdf)。鉴于这些要求非常有限,因此也欢迎其他解决方案。

     original.length row.retained percentage.retained
1               1875        FALSE                11.00
2               1143        FALSE                23.00
3                960        FALSE                44.00
4               1302        FALSE                66.00
5               2016        TRUE                 87.00

【问题讨论】:

    标签: python r ggplot2 rpy2 scatter-plot


    【解决方案1】:

    如果您对R 没有任何经验,但使用python,则可以使用numpypandas 进行数据分析,使用matplotlib 进行绘图。

    这是一个小例子,“这感觉如何”:

    import numpy as np
    import pandas as pd
    import matplotlib.pyplot as plt 
    
    df = pd.DataFrame({'original_length': [1875, 1143, 960, 1302, 2016],
                       'row_retained': [False, False, False, False, True],
                       'percentage_retained': [11.0, 23.0, 44.0, 66.0, 87.0]})
    fig, ax = plt.subplots()
    ax.scatter(df.original_length, df.percentage_retained,
               c=np.where(df.row_retained, 'green', 'red'),
               s=np.random.randint(50, 500, 5)
               )   
    true_value = df[df.row_retained]
    ax.annotate('This one is True',
                xy=(true_value.original_length, true_value.percentage_retained),
                xytext=(0.1, 0.001), textcoords='figure fraction',
                arrowprops=dict(arrowstyle="->"))
    ax.grid()
    ax.set_xlabel('Original Length')
    ax.set_ylabel('Precentage Retained')
    ax.margins(0.04)
    plt.tight_layout()
    plt.savefig('alternative.png')
    

    pandas 也有一个实验性的 rpy2 接口。

    【讨论】:

      【解决方案2】:

      R 包 ggplot2 中的更改破坏了 rpy2 层。 尝试使用 bitbucket 上 rpy2 代码的“默认”分支 (rpy2-2.3.0-dev) 的最新(我刚刚修复此问题)快照。

      编辑: rpy2-2.3.0 比计划晚了几个月。我刚刚发布了一个错误修复版本 rpy2-2.2.6,应该可以解决这个问题。

      【讨论】:

      • 您好,感谢您解决此问题!导入再次起作用,我正在考虑将我的代码转换为现在使用 rpy2 + ggplot2。
      【解决方案3】:

      问题是由最新的 ggplot2 版本 0.9.0 引起的。此版本没有 ggplot2 版本 0.8.9 中的 print.ggplot() 函数。

      我尝试修改 rpy2 代码以使其与最新的 ggplot2 一起使用,但更改的范围似乎很大。

      同时,只需将您的 ggplot2 版本降级到 0.8.9

      【讨论】:

        【解决方案4】:

        根据 fucitol 的回答,我改为使用默认绘图和格子来实现绘图。以下是两种实现方式:

        from rpy2 import robjects
        #Convert to R objects
        original_lengths = robjects.IntVector(original_lengths)
        percentages_retained = robjects.FloatVector(percentages_retained)
        row_retained = robjects.StrVector(row_retained)
        
        #Plot using standard plot
        r = robjects.r
        r.plot(x=percentages_retained,
               y=original_lengths,
               col=row_retained,
               main='Title',
               xlab='Percentage retained',
               ylab='Original length',
               sub='subtitle',
               pch=18)
        
        #Plot using lattice
        from rpy2.robjects import Formula
        from rpy2.robjects.packages import importr
        lattice = importr('lattice')
        formula = Formula('lengths ~ percentages')
        formula.getenvironment()['lengths'] = original_lengths
        formula.getenvironment()['percentages'] = percentages_retained
        
        p = lattice.xyplot(formula,
                           col=row_retained,
                           main='Title',
                           xlab='Percentage retained',
                           ylab='Original length',
                           sub='subtitle',
                           pch=18)
        rprint = robjects.globalenv.get("print")
        rprint(p)
        

        很遗憾我无法让ggplot2 工作,因为默认情况下它会生成更好的图表,而且我认为使用数据框更加明确。仍然欢迎这方面的任何帮助!

        【讨论】:

          【解决方案5】:

          虽然我无法帮助您修复您看到的导入错误,但这里有一个使用 lattice 的类似示例:lattice with rpy2

          此外,标准 R plot 函数通过使用 factor 函数接受着色(您可以提供 row.retained 列。示例:

          plot(original.length, percentage.retained, type="p", col=factor(row.retained))
          

          【讨论】:

            猜你喜欢
            • 2019-08-27
            • 2014-10-19
            • 2013-02-01
            • 2013-02-02
            • 2016-06-23
            • 2011-11-23
            • 2013-06-10
            • 2013-09-03
            • 2013-03-06
            相关资源
            最近更新 更多