rpy2 Scatter plot

rpy2で散布図を書く

import rpy2.robjects as robjects
from rpy2.robjects.packages import importr

grdevices = importr('grDevices')
grdevices.png(file="file.png", width=512, height=512)
# plotting code here

# 月齢
lstx = [0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0,
        10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0,
        20.0, 21.0, 22.0, 23.0, 24.0, 25.0, 26.0, 27.0, 28.0, 29.0]

# 漁獲高
lsty = [190.0, 200.0, 50.0, 1700.0, 360.0, 620.0, 450.0, 2100.0,
        120.0, 5000.0, 1900.0, 780.0, 880.0, 1500.0, 1500.0, 1900.0,
        200.0, 270.0, 2100.0, 7000.0, 900.0, 1200.0, 3700.0, 2000.0,
        2900.0, 1300.0, 140.0, 2250.0, 120.0, 1000.0]

rx = robjects.FloatVector(lstx)
ry = robjects.FloatVector(lsty)

robjects.r.plot(x=rx, y=ry, xlab="moon age", ylab="fish", col="blue")

grdevices.dev_off()

file
csvファイルから読み込む場合は、Rの命令文をそのまま書いてもよい

import rpy2.robjects as robjects
from rpy2.robjects.packages import importr
grdevices = importr('grDevices')
grdevices.png(file="file.png", width=512, height=512)

robjects.r('''
data <-read.csv('fish_moonage.csv', header=TRUE)
plot(fish~moonage, xlab="foo", data=data, col="purple")
''')

grdevices.dev_off()
Posted: August 27th, 2010 | Author: | Filed under: 技術 | Tags: , , , , | No Comments »

Using R from Python rpy2

Today I installed R (vesion2.11.1 2010.5.31) from mac installer.
R is an enviroment for statistical computing and graphics.
Python has some packages for R like rpy and rpy2.

Here is my install log.

install numpy and rpy2 via pip

pip install numpy
pip install rpy2
import rpy2.robjects as robjects                                                                                
                                                                                                                
ctl = robjects.FloatVector([4.17, 5.58, 5.18, 6.11, 4.50,                                                       
                            4.61, 5.17, 4.53, 5.33, 5.14])                                                      
trt = robjects.FloatVector([4.81, 4.17, 4.41, 3.59, 5.87,                                                       
                            3.83, 6.03, 4.89, 4.32, 4.69])                                                      
                                                                                                                
correlation = robjects.r('function(x, y) cor.test(x, y)')                                                       
print correlation(ctl, trt)                                                                                     
$ python Desktop/correlation_sample.py

	Pearson's product-moment correlation

data:  x and y 
t = -1.4559, df = 8, p-value = 0.1835
alternative hypothesis: true correlation is not equal to 0 
95 percent confidence interval:
 -0.8440680  0.2415684 
sample estimates:
       cor 
-0.4576683 
Posted: July 4th, 2010 | Author: | Filed under: 技術 | Tags: , , , , | No Comments »