在 Python 中使用 R 和 Rpy2:如何使用 ggplot2?

Using R in Python with Rpy2: how to ggplot2?

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

基本上我有一个包含 2 列、11 行且没有 header 的数据集,我想使用来自 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'

有人可以帮我理解我错在哪里吗?

也许您需要将数据框列与散点图的颜色相关联 点,以便 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: