Sage/text/R_in_Action (竹本氏のblog )
http://www.pwv.co.jp/~take/TakeWiki/index.php

R in Action Rob Kabacoff, 2014, Manning Publications

posted by Y.Sato on 30 Oct, 2014

In [1]:
%load_ext sage
In [2]:
import os
DATA = os.getcwd() + '/' ; DATA
Out[2]:
'/home/satouy/Dropbox/work-Sage/sage-ipython/Take/R_in_Action/'
In [3]:
# ChromeではPDFをimgタグで表示できないので、pngに変換するように変更 2012/06/27
#
# Rのグラフをsageで表示するためのユーティリティ関数
import time
def preGraph(pdfFile):
    filename = DATA+pdfFile
    r.pdf(file='"%s"' %filename)
    return pdfFile

def offGraph():
    r.dev_off()
    
def postGraph(pdfFile, fac=0.75):
    r.dev_off()
    width = int(640*fac)
    # html('<img src="%s?%s" width="%spx">'%(pdfFile, time.time(), width))
    pngFile = convertPdf2Png(pdfFile)
    html('<img src="%s?%s" width="%spx">'%(pngFile, time.time(), width))

def getGraph(pdfFile, fac=0.75):
    width = int(640*fac)
    # return '<img src="%s?%s" width="%spx">'%(pdfFile, time.time(), width)
    pngFile = convertPdf2Png(pdfFile)
    return '<img src="%s?%s" width="%spx">'%(pngFile, time.time(), width)
    
def convertPdf2Png(pdfFile):
    pngFile = pdfFile.replace(".pdf", ".png")
    result = os.popen("cd %s; convert -density 600 -geometry 1000 %s %s"%(DATA, pdfFile, pngFile)).read()
    # print result
    return pngFile 
In [4]:
from IPython.display import Image, display
In [5]:
from IPython.display import display, Math
def my_show(obj):
    return display(Math(latex(obj)))
In [6]:
class ListTable(list):
    """ Overridden list class which takes a 2-dimensional list of 
        the form [[1,2,3],[4,5,6]], and renders an HTML Table in 
        IPython Notebook. """
    
    def _repr_html_(self):
        html = ["<table>"]
        for row in self:
            html.append("<tr>")
            
            for col in row:
                html.append("<td>{0}</td>".format(col))
            
            html.append("</tr>")
        html.append("</table>")
        return ''.join(html)
In [7]:
# table = ListTable()
# table.append([getGraph(fig_3_7a, fac=0.5), getGraph(fig_3_7b, fac=0.5)])
# table
In [8]:
from IPython.display import HTML

Begin of program

Chapter 11 Intermediate graphics

In [9]:
# fig 11.1
fig11_1 = preGraph("fig11.1.pdf")
r('attach(mtcars)')
r('plot(wt, mpg, main="Basic Scatter plot of MPG vs. Weight", xlab="Car Weight (lbs/1000)", ylab="Miles Per Gallon ", pch=19)')
r('abline(lm(mpg~wt), col="red", lwd=2, lty=1)')
r('lines(lowess(wt,mpg), col="blue", lwd=2, lty=2)') 
postGraph(fig11_1, fac=0.6) 
<html><font color='black'><img src="fig11.1.png?1414661105.95" width="384px"></font></html>
In [10]:
os.system("convert -resize 400x fig11.1.png fig11.1b.png")
display(Image('fig11.1b.png'))
In [11]:
# fig 11.3
fig11_3 = preGraph("fig11.3.pdf")
r('pairs(~mpg+disp+drat+wt, data=mtcars, main="Basic Scatter Plot Matrix")')
postGraph(fig11_3, fac=0.6) 
<html><font color='black'><img src="fig11.3.png?1414661108.28" width="384px"></font></html>
In [12]:
os.system("convert -resize 400x fig11.3.png fig11.3b.png")
display(Image('fig11.3b.png'))
In [13]:
# 散布図がつぶれてしまったような場合の対処方法
r('set.seed(1234)')
r('n <- 10000')
r('c1 <- matrix(rnorm(n, mean=0, sd=.5), ncol=2)')
r('c2 <- matrix(rnorm(n, mean=3, sd=2), ncol=2)')
r('mydata <- rbind(c1, c2)')
r('mydata <- as.data.frame(mydata)')
r('names(mydata) <- c("x", "y")') 
Out[13]:
[1] "x" "y"
In [14]:
fig11_7 = preGraph("fig11.7.pdf")
r('with(mydata, plot(x, y, pch=19, main="Scatter Plot with 10,000 Observations"))')
postGraph(fig11_7, fac=0.6) 
<html><font color='black'><img src="fig11.7.png?1414661113.71" width="384px"></font></html>
In [15]:
os.system("convert -resize 400x fig11.7.png fig11.7b.png")
display(Image('fig11.7b.png'))
In [16]:
# fig 11.8
fig11_8 = preGraph("fig11.8.pdf")
r('with(mydata, smoothScatter(x, y, main="Scatterplot Colored by Smoothed Densities"))')
postGraph(fig11_8, fac=0.6) 
<html><font color='black'><img src="fig11.8.png?1414661117.06" width="384px"></font></html>
In [17]:
os.system("convert -resize 400x fig11.8.png fig11.8b.png")
display(Image('fig11.8b.png'))
In [18]:
r('ftable(Titanic)') 
Out[18]:
                   Survived  No Yes
Class Sex    Age                   
1st   Male   Child            0   5
             Adult          118  57
      Female Child            0   1
             Adult            4 140
2nd   Male   Child            0  11
             Adult          154  14
      Female Child            0  13
             Adult           13  80
3rd   Male   Child           35  13
             Adult          387  75
      Female Child           17  14
             Adult           89  76
Crew  Male   Child            0   0
             Adult          670 192
      Female Child            0   0
             Adult            3  20
In [19]:
# fig 11.23
#r('install.packages("vcd")')
r('library(vcd)')
fig11_23 = preGraph("fig11.23.pdf")
r('mosaic(Titanic, shade=TRUE, legend=TRUE)')
postGraph(fig11_23, fac=0.6) 
<html><font color='black'><img src="fig11.23.png?1414661126.32" width="384px"></font></html>
In [20]:
os.system("convert -resize 400x fig11.23.png fig11.23b.png")
display(Image('fig11.23b.png'))
In [20]: