【问题标题】:Using R in Python with Rpy2: how to ggplot2?在 Python 中使用 R 和 Rpy2:如何使用 ggplot2?
【发布时间】:2016-05-11 04:40:22
【问题描述】:

我正在尝试在 Python 中使用 R,我发现 Rpy2 非常有趣。它功能强大且使用起来并不难,但是即使我阅读了文档并寻找了类似的问题,我也无法使用 ggplot2 库解决我的问题。

基本上我有一个包含 2 列、11 行且没有标题的数据集,我想使用 Python 中的这个 R 代码做一个散点图:

ggplot(dataset,aes(dataset$V1, dataset$V2))+geom_point()+scale_color_gradient(low="yellow",high="red")+geom_smooth(method='auto')+labs(title = "Features distribution on Scaffolds", x='Scaffolds Length', y='Number of Features')

我已经在 R 中测试了这段代码(在 read.table 我的文件之后)并且它可以工作。现在,这是我的 python 脚本:

import math, datetime
import rpy2
import rpy2.robjects as robjects
import rpy2.robjects.lib.ggplot2 as ggplot2

r = robjects.r
df = r("read.table('file_name.txt',sep='\t', header=F)")
gp = ggplot2.ggplot(df, ggplot2.aes(df[0], df[1])) + ggplot2.geom_point() + ggplot2.scale_color_gradient(low="yellow",high="red") + ggplot2.geom_smooth(method='auto') + ggplot2.labs(title = "Features distribution on Scaffolds", x='Scaffolds Length', y='Number of Features')
gp.plot()

如果我运行这个 Python 代码,它会给我两个错误。第一个是:

gp = ggplot2.ggplot(df, ggplot2.aes(df[0], df[1]))
TypeError: new() takes exactly 1 argument (3 given)

第二个是:

AttributeError: 'module' object has no attribute 'scale_color_gradient'

谁能帮我理解我错在哪里?

【问题讨论】:

    标签: r python-2.7 ggplot2 rpy2


    【解决方案1】:

    也许您需要将数据框列与散点图的颜色相关联 点以便scale_colour_gradient 可以关联到该列:

    import numpy as np
    import pandas as pd
    import rpy2.robjects.packages as packages
    import rpy2.robjects.lib.ggplot2 as ggplot2
    import rpy2.robjects as ro
    R = ro.r
    datasets = packages.importr('datasets')
    mtcars = packages.data(datasets).fetch('mtcars')['mtcars']
    gp = ggplot2.ggplot(mtcars)
    pp = (gp 
          + ggplot2.aes_string(x='wt', y='mpg')
          + ggplot2.geom_point(ggplot2.aes_string(colour='qsec'))
          + ggplot2.scale_colour_gradient(low="yellow", high="red") 
          + ggplot2.geom_smooth(method='auto') 
          + ggplot2.labs(title="mtcars", x='wt', y='mpg'))
    
    pp.plot()
    R("dev.copy(png,'/tmp/out.png')")
    


    错误

    gp = ggplot2.ggplot(df, ggplot2.aes(df[0], df[1]))
    TypeError: new() takes exactly 1 argument (3 given)
    

    发生是因为 ggplot2.ggplot 只接受 1 个参数,即数据框:

    gp = ggplot2.ggplot(df)
    

    然后您可以将美学映射添加到gp

    gp + ggplot2.aes_string(x='0', y='1')
    

    其中'0''1'df 的列名。根据examples in the docs,我在这里使用aes_string 而不是aes


    第二个错误

    AttributeError: 'module' object has no attribute 'scale_color_gradient'
    

    发生是因为 ggplot2 使用颜色的英国拼写:scale_colour_gradient:

    【讨论】:

    • 我已按照您的提示更改了我的代码,并且效果很好!非常感谢您的帮助,希望我能尽快达到 15 级以对您的评论进行投票。再次感谢你:)
    • 美式拼写将很快添加。感谢您指出@unutbu
    • 当我在 Colab 中尝试这个时,它只输出带有 1 个元素的 IntVector。 5而不是情节。如何解决?
    猜你喜欢
    • 2018-12-30
    • 1970-01-01
    • 2019-10-21
    • 2019-09-14
    • 2013-06-10
    • 2016-01-15
    • 2013-02-22
    • 1970-01-01
    • 2020-03-07
    相关资源
    最近更新 更多