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 3 Getting started with graphics

In [9]:
# fig 3.1
fig_3_1 = preGraph("fig3.1.pdf")
r('attach(mtcars)')
r('plot(wt, mpg)')
r('abline(lm(mpg~wt))')
r('title("Regression of MPG on Weight")')
r('detach(mtcars)')
postGraph(fig_3_1, fac=0.5) 
<html><font color='black'><img src="fig3.1.png?1414660491.53" width="320px"></font></html>
In [10]:
os.system("convert -resize 400x fig3.1.png fig3.1b.png")
display(Image('fig3.1b.png'))
In [11]:
# fig 3.2
dose = r.c([20, 30, 40, 45, 60]).name('dose')
drugA = r.c([16, 20, 27, 40, 60]).name('drugA')
drugB = r.c([15, 18, 25, 31, 40]).name('drugB')
In [12]:
fig_3_2 = preGraph("fig3.2.pdf")
r('plot(dose, drugA, type="b")')
postGraph(fig_3_2, fac=0.5) 
<html><font color='black'><img src="fig3.2.png?1414660493.89" width="320px"></font></html>
In [13]:
os.system("convert -resize 400x fig3.2.png fig3.2b.png")
display(Image('fig3.2b.png'))

html.table( )

In [14]:
# fig 3.7
fig_3_7a = preGraph("fig3.7a.pdf")
r('par(pin=c(2, 3))')
r('par(lwd=2, cex=1.5)')
r('par(cex.axis=.75, font.axis=3)')
r('plot(dose, drugA, type="b", pch=19, lty=2, col="red")')
offGraph() 
In [15]:
# parは、プロット毎にセットしないとダメ
fig_3_7b = preGraph("fig3.7b.pdf")
r('par(pin=c(2, 3))')
r('par(lwd=2, cex=1.5)')
r('par(cex.axis=.75, font.axis=3)')
r('plot(dose, drugB, type="b", pch=23, lty=6, col="blue", bg="green")')
#r.par(opar)
offGraph()
In [16]:
html.table([[getGraph(fig_3_7a, fac=0.5), getGraph(fig_3_7b, fac=0.5)]])
<html>
<div class="notruncate">
<table  class="table_form">
<tbody>
<tr class ="row-a">
<td><img src="fig3.7a.png?1414660496.22" width="320px"></td>
<td><img src="fig3.7b.png?1414660498.2" width="320px"></td>
</tr>
</tbody>
</table>
</div>
</html>
In [17]:
# from IPython.display import HTML
In [18]:
s = """<div class="notruncate">
<table  class="table_form" >
<tbody>
<tr class ="row-a">
<td><img src="fig3.7a.png?1413623388.94" width="320px"></td>
<td><img src="fig3.7b.png?1413623393.31" width="320px"></td>
</tr>
</tbody>
</table>
</div>"""
In [19]:
h = HTML(s); h
Out[19]:
In [20]:
table = ListTable()
table.append([getGraph(fig_3_7a, fac=0.5), getGraph(fig_3_7b, fac=0.5)])
table
Out[20]:
In [21]:
# fig 3.8
fig_3_8 = preGraph("fig3.8.pdf")
r('plot(dose, drugA, type="b", col="red", lty=2, pch=2, lwd=2, main="Clinical Trials for Drug A", sub="This is hypothetical data", xlab="Dosage", ylab="Drug Response", xlim=c(0, 60), ylim=c(0, 70))')
postGraph(fig_3_8, fac=0.5) 
<html><font color='black'><img src="fig3.8.png?1414660505.0" width="320px"></font></html>
In [22]:
os.system("convert -resize 400x fig3.8.png fig3.8b.png")
display(Image('fig3.8b.png'))
In [23]:
# fig 3.9
x = r('c(1:10)').name('x')
y = r('x').name('y')
z = r('10/x').name('z')
print x
print y
print z 
 [1]  1  2  3  4  5  6  7  8  9 10
 [1]  1  2  3  4  5  6  7  8  9 10
 [1] 10.000000  5.000000  3.333333  2.500000  2.000000  1.666667  1.428571  1.250000  1.111111
[10]  1.000000
In [24]:
fig_3_9 = preGraph("fig3.9.pdf")
opar = r('par(no.readlonly=TRUE)').name('opar')
r('par(mar=c(5, 4, 4, 8) + 0.1)')
r('plot(x, y, type="b", pch=21, col="red", yaxt="n", lty=3, ann=FALSE)')
r('lines(x, z, type="b", pch=22, col="blue", lty=2)')
r('axis(2, at=x, labels=x, col.axis="red", las=2)')
r('axis(4, at=z, labels=round(z, digits=2), col.axis="blue", las=2, cex.axis=0.7, tck=-.01)')
r('mtext("y=1/x", side=4, line=3, cex.lab=1, las=2, col="blue")')
r('title("An Example of Creative Axes", xlab="X values", ylab="Y=X")')
r.par(opar)
postGraph(fig_3_9, fac=0.5) 
<html><font color='black'><img src="fig3.9.png?1414660507.69" width="320px"></font></html>
In [25]:
os.system("convert -resize 400x fig3.9.png fig3.9b.png")
display(Image('fig3.9b.png'))
In [26]:
# fig3.10
r('library(Hmisc)')

fig_3_10 = preGraph("fig3.10.pdf")
opar = r('par(no.readlonly=TRUE)').name('opar')
r('par(lwd=2, cex=1.5, font.lab=2)')
r('plot(dose, drugA, type="b", pch=15, lty=1, col="red", ylim=c(0, 60), main="Drug A vs. Drug B", xlab="Drug Dosage", ylab="Drug Response")')
r('lines(dose, drugB, type="b", pch=17, lty=2, col="blue")')
r('abline(h=c(30), lwd=1.5, lty=2, col="gray")')
r('minor.tick(nx=3, ny=3, tick.ratio=0.5)')
r('legend("topleft", inset=.05, title="Drug Type", c("A","B"), lty=c(1, 2), pch=c(15, 17), col=c("red", "blue"))')
r.par(opar)
postGraph(fig_3_10, fac=0.5) 
<html><font color='black'><img src="fig3.10.png?1414660510.0" width="320px"></font></html>
In [27]:
os.system("convert -resize 400x fig3.10.png fig3.10b.png")
display(Image('fig3.10b.png'))
In [28]:
# fig 3.11
r('attach(mtcars)')
fig_3_11 = preGraph("fig3.11.pdf")
r('plot(wt, mpg, main="Mileage vs. Car Weight", xlab="Weight", ylab="Mileage", pch=18, col="blue")')
r('text(wt, mpg, row.names(mtcars), cex=0.6, pos=4, col="red")')
postGraph(fig_3_11, fac=0.7)
r('detach(mtcars)') 
<html><font color='black'><img src="fig3.11.png?1414660512.19" width="448px"></font></html>
Out[28]:
<environment: 0x17fbf48>
attr(,"name")
[1] "mtcars"
In [29]:
os.system("convert -resize 400x fig3.11.png fig3.11b.png")
display(Image('fig3.11b.png'))
In [30]:
# fig 3.12
fig_3_12 = preGraph("fig3.12.pdf")
opar = r('par(no.readlonly=TRUE)').name('opar')
r('par(cex=1.5)')
r('plot(1:7,1:7,type="n")')
r('text(3,3,"Example of default text")')
r('text(4,4,family="mono","Example of mono-spaced text")')
r('text(5,5,family="serif","Example of serif text")')
r.par(opar)
postGraph(fig_3_12, fac=0.5) 
<html><font color='black'><img src="fig3.12.png?1414660514.33" width="320px"></font></html>
In [31]:
os.system("convert -resize 400x fig3.12.png fig3.12b.png")
display(Image('fig3.12b.png'))
In [32]:
# fig 3.14
fig_3_14 = preGraph("fig3.14.pdf")
r('attach(mtcars)')
opar = r('par(no.readlonly=TRUE)').name('opar')
r('par(mfrow=c(2,2))')
r('plot(wt,mpg, main="Scatterplot of wt vs. mpg")')
r('plot(wt,disp, main="Scatterplot of wt vs disp")')
r('hist(wt, main="Histogram of wt")')
r('boxplot(wt, main="Boxplot of wt")')
r.par(opar)
r('detach(mtcars)')
postGraph(fig_3_14, fac=0.6)
<html><font color='black'><img src="fig3.14.png?1414660516.44" width="384px"></font></html>
In [33]:
os.system("convert -resize 400x fig3.14.png fig3.14b.png")
display(Image('fig3.14b.png'))
In [34]:
# fig 3.15
fig_3_15 = preGraph("fig3.15.pdf")
r('attach(mtcars)')
opar = r('par(no.readlonly=TRUE)').name('opar')
r('par(mfrow=c(3,1))')
r('hist(wt)')
r('hist(mpg)')
r('hist(disp)')
r.par(opar)
r('detach(mtcars)')
postGraph(fig_3_15, fac=0.6) 
<html><font color='black'><img src="fig3.15.png?1414660518.64" width="384px"></font></html>
In [35]:
os.system("convert -resize 400x fig3.15.png fig3.15b.png")
display(Image('fig3.15b.png'))
In [36]:
# fig 3.18
fig_3_18 = preGraph("fig3.18.pdf")
opar = r('par(no.readlonly=TRUE)').name('opar')
# Set up scatter plot
r('par(fig=c(0, 0.8, 0, 0.8))')
r('plot(mtcars$wt, mtcars$mpg, xlab="Miles Per Gallon", ylab="Car Weight")')
# Add box plot above     
r('par(fig=c(0, 0.8, 0.55, 1), new=TRUE)')
r('boxplot(mtcars$wt, horizontal=TRUE, axes=FALSE)')
# Add box plot to right
r('par(fig=c(0.65, 1, 0, 0.8), new=TRUE)')
r('boxplot(mtcars$mpg, axes=FALSE)')
r('mtext("Enhanced Scatterplot", side=3, outer=TRUE, line=-3)')
r.par(opar)
postGraph(fig_3_18, fac=0.6) 
<html><font color='black'><img src="fig3.18.png?1414660520.72" width="384px"></font></html>
In [37]:
os.system("convert -resize 400x fig3.18.png fig3.18b.png")
display(Image('fig3.18b.png'))