r - 在 Python 中使用 R 和 Rpy2 : how to ggplot2?

标签 r python-2.7 ggplot2 rpy2

我正在尝试在 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'

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

最佳答案

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

enter image description here

<小时/>

错误

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:

关于r - 在 Python 中使用 R 和 Rpy2 : how to ggplot2?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35152395/

相关文章:

r - 如何在 R 中绘制 Fisher LDA 的决策边界?

r - 按组在ggplot中颜色和更改线型

r - 根据序列同时添加多个列

r - dummy_cols 错误 : vector memory exhausted (limit reached? )

r - 与单位无关的position_nudge

Python GTK+3教程--窗口显得过大,不像示例图片

python - Ubuntu 中的多个版本的 Python

python - 打印/输出时如何从列表中删除方括号

r - 在 tikzDevice 中使用 tikzAnnotate 注释 ggplot2 图

r - 如何强制y轴达到R的最小和最大范围?