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 6 Basic graphics

In [9]:
# Sec 6.1.1 Simple bar plots
# vcdパッケージを使用するため、1回のみ実行
#r('install.packages("vcd")') 
r("library(vcd)") 
Out[9]:
 エラー:  オブジェクト 'sage0' がありません 
In [10]:
counts = r("table(Arthritis$Improved)").name('counts'); counts 
Out[10]:
 エラー:  オブジェクト 'counts' がありません 
In [11]:
# fig 6.1a
fig6_1a = preGraph("fig6.1a.pdf")
r('barplot(counts, main="Simple Bar Plot", xlab="Improvement", ylab="Frequency")')
offGraph() 
In [12]:
# fig 6.1b
fig6_1b = preGraph("fig6.1b.pdf")
r('barplot(counts, main="Horizontal Bar Plot", xlab="Frequency", ylab="Improvement", horiz=TRUE)')
offGraph() 
In [13]:
# html.table([[getGraph(fig6_1a, fac=0.5), getGraph(fig6_1b, fac=0.5)]]) 
In [14]:
table = ListTable()
table.append([getGraph(fig6_1a, fac=0.5), getGraph(fig6_1b, fac=0.5)])
table
Out[14]:
In [15]:
# Sec. 6.2
counts = r("table(Arthritis$Improved, Arthritis$Treatment)").name('counts'); counts 
Out[15]:
[1] "/home/satouy/Dropbox/work-Sage/sage-ipython/Take/R_in_Action/fig6.1b.pdf"
In [16]:
# fig 6.2
fig6_2a = preGraph("fig6.2a.pdf")
r('barplot(counts, main="Stacked Bar Plot", xlab="Treatment", ylab="Frequency", col=c("red", "yellow","green"), legend=rownames(counts))')
offGraph()
fig6_2b = preGraph("fig6.2b.pdf")
r('barplot(counts, main="Grouped Bar Plot", xlab="Treatment", ylab="Frequency", col=c("red", "yellow", "green"), legend=rownames(counts), beside=TRUE)')
offGraph()
# html.table([[getGraph(fig6_2a, fac=0.5), getGraph(fig6_2b, fac=0.5)]]) 
In [17]:
table = ListTable()
table.append([getGraph(fig6_2a, fac=0.5), getGraph(fig6_2b, fac=0.5)])
table
Out[17]:
In [18]:
# fig 6.5
fig6_5 = preGraph("fig6.5.pdf")
r('attach(Arthritis)')
r('counts <- table(Treatment, Improved)')
r('spine(counts, main="Spinogram Example")')
r('detach(Arthritis)')
postGraph(fig6_5, fac=0.6) 
<html><font color='black'><img src="fig6.5.png?1414660608.62" width="384px"></font></html>
In [19]:
os.system("convert -resize 400x fig6.5.png fig6.5b.png")
display(Image('fig6.5b.png'))
In [20]:
# plotrixパッケージを使用するため、1回のみ実行
r('install.packages("plotrix")') 
Out[20]:
NULL
In [21]:
# fig 6.6
fig6_6 = preGraph("fig6.6.pdf")
r('par(mfrow=c(2, 2))')
r('slices <- c(10, 12,4, 16, 8)')
r('lbls <- c("US", "UK", "Australia", "Germany", "France")')
r('pie(slices, labels = lbls, main="Simple Pie Chart")')
r('pct <- round(slices/sum(slices)*100)')
r('lbls2 <- paste(lbls, " ", pct, "%", sep="")')
r('pie(slices, labels=lbls2, col=rainbow(length(lbls2)), main="Pie Chart with Percentages")')
r('library(plotrix)')
r('pie3D(slices, labels=lbls,explode=0.1, main="3D Pie Chart ")')
r('mytable <- table(state.region)')
r('lbls3 <- paste(names(mytable), "\n", mytable, sep="")')
r('pie(mytable, labels = lbls3, main="Pie Chart from a Table\n (with sample sizes)")')
postGraph(fig6_6, fac=0.6) 
<html><font color='black'><img src="fig6.6.png?1414660614.05" width="384px"></font></html>
In [22]:
os.system("convert -resize 400x fig6.6.png fig6.6b.png")
display(Image('fig6.6b.png'))
In [23]:
# fig 6.7
fig6_7 = preGraph("fig6.7.pdf")
r('fan.plot(slices, labels = lbls, main="Fan Plot")')
postGraph(fig6_7, fac=0.6) 
<html><font color='black'><img src="fig6.7.png?1414660616.15" width="384px"></font></html>
In [24]:
os.system("convert -resize 400x fig6.7.png fig6.7b.png")
display(Image('fig6.7b.png'))
In [25]:
# fig 6.8
fig6_8 = preGraph("fig6.8.pdf")
r('par(mfrow=c(2,2))')
r('hist(mtcars$mpg)')
r('hist(mtcars$mpg, breaks=12, col="red", xlab="Miles Per Gallon", main="Colored histogram with 12 bins")')
r('hist(mtcars$mpg, freq=FALSE, breaks=12, col="red", xlab="Miles Per Gallon", main="Histogram, rug plot, density curve")')
r('rug(jitter(mtcars$mpg))')
r('lines(density(mtcars$mpg), col="blue", lwd=2)')
r('x <- mtcars$mpg')
r('h<-hist(x, breaks=12, col="red", xlab="Miles Per Gallon", main="Histogram with normal curve and box")')
r('xfit<-seq(min(x), max(x), length=40)')
r('yfit<-dnorm(xfit, mean=mean(x), sd=sd(x))')
r('yfit <- yfit*diff(h$mids[1:2])*length(x)')
r('lines(xfit, yfit, col="blue", lwd=2)')
r('box()')
postGraph(fig6_8, fac=0.7) 
<html><font color='black'><img src="fig6.8.png?1414660618.55" width="448px"></font></html>
In [26]:
os.system("convert -resize 400x fig6.8.png fig6.8b.png")
display(Image('fig6.8b.png'))
In [27]:
# fig 6.9
fig6_9 = preGraph("fig6.9.pdf")
r('par(mfrow=c(2,1))')
r('d <- density(mtcars$mpg)')
r('plot(d)')
r('plot(d, main="Kernel Density of Miles Per Gallon")')
r('polygon(d, col="red", border="blue")')
r('rug(mtcars$mpg, col="brown")')
postGraph(fig6_9, fac=0.6) 
<html><font color='black'><img src="fig6.9.png?1414660620.75" width="384px"></font></html>
In [28]:
os.system("convert -resize 400x fig6.9.png fig6.9b.png")
display(Image('fig6.9b.png'))
In [29]:
# smパッケージを使用するため、1回のみ実行
r('install.packages("sm")') 
Out[29]:
NULL
In [30]:
# fig 6.10
# 凡例が表示されない
fig6_10 = preGraph("fig6.10.pdf")
r('par(lwd=2)')
r('library(sm)')
r('attach(mtcars)')
r('cyl.f <- factor(cyl, levels= c(4,6,8), labels = c("4 cylinder", "6 cylinder", "8 cylinder"))')
r('sm.density.compare(mpg, cyl, xlab="Miles Per Gallon")')
r('title(main="MPG Distribution by Car Cylinders")')
r('colfill<-c(2:(1+length(levels(cyl.f))))')
r('legend(locator(1), levels(cyl.f), fill=colfill)')
r('detach(mtcars)')
postGraph(fig6_10, fac=0.6) 
<html><font color='black'><img src="fig6.10.png?1414660625.5" width="384px"></font></html>
In [31]:
os.system("convert -resize 400x fig6.10.png fig6.10b.png")
display(Image('fig6.10b.png'))
In [32]:
# fig 6.14
fig6_14 = preGraph("fig6.14.pdf")
r('mtcars$cyl.f <- factor(mtcars$cyl, levels=c(4,6,8), labels=c("4","6","8"))')
r('mtcars$am.f <- factor(mtcars$am, levels=c(0,1), labels=c("auto", "standard"))')
r('boxplot(mpg ~ am.f *cyl.f, data=mtcars, varwidth=TRUE, col=c("gold","darkgreen"), main="MPG Distribution by Auto Type", xlab="Auto Type")')
postGraph(fig6_14, fac=0.6) 
<html><font color='black'><img src="fig6.14.png?1414660627.63" width="384px"></font></html>
In [33]:
os.system("convert -resize 400x fig6.14.png fig6.14b.png")
display(Image('fig6.14b.png'))
In [34]:
# fig 6.16
fig6_16 = preGraph("fig6.16.pdf")
r('dotchart(mtcars$mpg, labels=row.names(mtcars), cex=.7, main="Gas Mileage for Car Models", xlab="Miles Per Gallon")')
postGraph(fig6_16, fac=0.6) 
<html><font color='black'><img src="fig6.16.png?1414660629.9" width="384px"></font></html>
In [35]:
os.system("convert -resize 400x fig6.16.png fig6.16b.png")
display(Image('fig6.16b.png'))