使用Rpy2在Python中使用R:如何绘制ggplot2图形?

5
我正在尝试在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中测试了这段代码(在读取文件后),它可以正常工作。现在,这是我的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'

请问有人能帮我理解我错在哪里吗?

1个回答

13
也许您需要将数据框的列与散点图的颜色关联起来,以便可以将 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只接受一个参数——数据框。

gp = ggplot2.ggplot(df)

您可以将美学映射添加到 gp 中:
gp + ggplot2.aes_string(x='0', y='1')

'0''1'df的列名。根据文档中的示例,我在这里使用了aes_string而不是aes


第二个错误

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

发生这种情况是因为ggplot2使用了英式拼写的颜色:scale_colour_gradient


我根据您的建议修改了我的代码,现在它运行得非常好!非常感谢您的帮助,希望我能尽快达到15级以点赞您的评论。再次感谢您 :) - Revo
美国拼写很快就会添加。感谢@unutbu指出。 - lgautier
当我在Colab中尝试时,它只输出一个元素为5的IntVector,而不是图表。如何解决? - WebComer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接