且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-06-19 01:37:19

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

Perhaps you need to associate a dataframe column to the colour of the scatter points so that the scale_colour_gradient can be associated to that column:

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个参数,即数据帧:

occurred because ggplot2.ggplot takes only 1 argument, the dataframe:

gp = ggplot2.ggplot(df)

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

You can then add the aesthetics mapping to gp:

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

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

where '0' and '1' are column names of df. Per the examples in the docs, I've used aes_string here instead of aes.

第二个错误

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

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

occurred because ggplot2 uses the British spelling of color: scale_colour_gradient: