%load_ext sage
import os
DATA = os.getcwd() + '/' ; DATA
# 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(''%(pdfFile, time.time(), width))
pngFile = convertPdf2Png(pdfFile)
html(''%(pngFile, time.time(), width))
def getGraph(pdfFile, fac=0.75):
width = int(640*fac)
# return ''%(pdfFile, time.time(), width)
pngFile = convertPdf2Png(pdfFile)
return ''%(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
from IPython.display import Image, display
from IPython.display import display, Math
def my_show(obj):
return display(Math(latex(obj)))
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 = ["
"]
for row in self:
html.append("")
for col in row:
html.append("{0} | ".format(col))
html.append("
")
html.append("
")
return ''.join(html)
# table = ListTable()
# table.append([getGraph(fig_3_7a, fac=0.5), getGraph(fig_3_7b, fac=0.5)])
# table
from IPython.display import HTML
# Sec 6.1.1 Simple bar plots
# vcdパッケージを使用するため、1回のみ実行
#r('install.packages("vcd")')
r("library(vcd)")
counts = r("table(Arthritis$Improved)").name('counts'); counts
# fig 6.1a
fig6_1a = preGraph("fig6.1a.pdf")
r('barplot(counts, main="Simple Bar Plot", xlab="Improvement", ylab="Frequency")')
offGraph()
# fig 6.1b
fig6_1b = preGraph("fig6.1b.pdf")
r('barplot(counts, main="Horizontal Bar Plot", xlab="Frequency", ylab="Improvement", horiz=TRUE)')
offGraph()
# html.table([[getGraph(fig6_1a, fac=0.5), getGraph(fig6_1b, fac=0.5)]])
table = ListTable()
table.append([getGraph(fig6_1a, fac=0.5), getGraph(fig6_1b, fac=0.5)])
table
# Sec. 6.2
counts = r("table(Arthritis$Improved, Arthritis$Treatment)").name('counts'); counts
# 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)]])
table = ListTable()
table.append([getGraph(fig6_2a, fac=0.5), getGraph(fig6_2b, fac=0.5)])
table
# 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)
os.system("convert -resize 400x fig6.5.png fig6.5b.png")
display(Image('fig6.5b.png'))
# plotrixパッケージを使用するため、1回のみ実行
r('install.packages("plotrix")')
# 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)
os.system("convert -resize 400x fig6.6.png fig6.6b.png")
display(Image('fig6.6b.png'))
# fig 6.7
fig6_7 = preGraph("fig6.7.pdf")
r('fan.plot(slices, labels = lbls, main="Fan Plot")')
postGraph(fig6_7, fac=0.6)
os.system("convert -resize 400x fig6.7.png fig6.7b.png")
display(Image('fig6.7b.png'))
# 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)
os.system("convert -resize 400x fig6.8.png fig6.8b.png")
display(Image('fig6.8b.png'))
# 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)
os.system("convert -resize 400x fig6.9.png fig6.9b.png")
display(Image('fig6.9b.png'))
# smパッケージを使用するため、1回のみ実行
r('install.packages("sm")')
# 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)
os.system("convert -resize 400x fig6.10.png fig6.10b.png")
display(Image('fig6.10b.png'))
# 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)
os.system("convert -resize 400x fig6.14.png fig6.14b.png")
display(Image('fig6.14b.png'))
# 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)
os.system("convert -resize 400x fig6.16.png fig6.16b.png")
display(Image('fig6.16b.png'))