# R을 이용한 통계 프로그래밍 기초

# 3. R 그래프

# 3.1 간단한 그래프

x = seq(-pi,pi,0.1)
cosy = cos(x)
plot(x, cosy) # 그래프 그리기

siny = sin(x)
plot(siny ~ x) # 그래프 그리기

jpeg("03.jpg")
par(mfrow = c(2,1)) # 2행 1열의 그래프 레이아웃 생성
plot(x, cosy) # 위에서 생성한 레이아웃의 첫째에 그래프 그리기
text(3,0, "cos(x)") # 그래프 위의 x=3, y=0의 위치에 글자 쓰기
plot(siny ~ x) # 위에서 생성한 레이아웃의 둘째에 그래프 그리기
text(2,0, "sin(x)") # 그래프 위의 x=2, y=0의 위치에 글자 쓰기
dev.off()


x = (0:20)*pi/10 # x축 데이터 생성
y = cos(x)
ysin = sin(x)
ysin2 = sin(x)^2

jpeg("04.jpg")
par(mfrow = c(1,2)) # 행 1, 열 2의 레이아웃 생성

yy = cbind(y, ysin, ysin2) # y 벡터를 결합
matplot(x, yy, type = "pll", pch="*") # matplot을 이용한 한 평면에 여러 그래프 그리기

plot(x,y) # 그래프 그리기
lines(x, ysin, type="p", pch="*") # 기존 그래프에 추가하여 그리기
lines(x, ysin2) # 기존 그래프에 추가하여 그리기
dev.off()


# 3.2 그래프 조절 변수

jpeg("05.jpg")
op = par(mfrow = c(2,2)) # 행 2, 열 2의 레이아웃 생성
plot(x, y, type = "p") # point로 된 그래프
plot(x, y, type = "l") # line으로 된 그래프
plot(x, y, type = "b") # both(point and line)로 된 그래프
plot(x, y, type = "p", pch=19, col="red") # point(표시기호 19, red)로 된 그래프
par(op)
dev.off()

jpeg("06.jpg")
plot(c(0,7),c(1,7), type="n", ylab=" ", xlab=" ", axes=FALSE, main="line type")
# nothing 그래프를 그리지 않는다. 축을 그리지 않는다.
for (i in 1:6) {
lines(c(0,7), c(i, i), lty=i) # 현재 그래프에 그리기
axis(2,at=i, labels=paste("lty=",i), las=1) # 축 추가하기
}
dev.off()

jpeg("07.jpg")
op = par(mfrow = c(2,2)) # 행 2, 열 2의 레이아웃
plot(x, y, type="b", main="Cos graph", sub="type = both(point and line)") # type = both(point and line)
plot(x, y, type="o", las=1,bty = "u", sub = "type=overplotted")# type = overplotted, box type = u, las = 축의 눈금값을 수평방향으로 표시
plot(x, y, type="h", bty="7", sub="type=h") # type=histogram, box type=7
plot(x, y, type="s", bty="n", sub="type=s") # step line, box type = n
par(op) # 레이아웃 끝
dev.off()


data(cars) # cars 데이터 사용하기
summary(cars)
jpeg("08.jpg")
op = par(mfrow = c(2,2)) # 행 2, 열 2의 레이아웃
plot(cars$speed, cars$dist, pch=1) # 그래프 그리기
abline(v = mean(cars$speed)) # speed의 평균에 수직선(v) 그리기
plot(cars$speed, cars$dist, pch=2) # 그래프 그리기
abline(h = mean(cars$dist)) # dist의 평균에 수평선(h) 그리기
plot(cars$speed, cars$dist, pch=3) # 그래프 그리기
abline(-17, 4) # 절편 -17, 기울기 4의 그래프 그리기
plot(cars$speed, cars$dist, pch=8) # 그래프 그리기
abline(v = mean(cars$speed)) # speed의 평균에 수직선(v) 그리기
abline(h = mean(cars$dist)) # dist의 평균에 수평선(h) 그리기
par(op)
dev.off()

# 예 3.2
pr = data.frame(animal = c("potar monkey", "gorilla", "human", "Rhesus monkey", "chimp"),
bodywt = c(10, 207, 62, 6.8, 52.2),
brainwt = c(115, 406, 1320, 179, 440))
pr # 입력 자료 확인
attributes(pr) # 속성 확인
win.graph() # windows graphics device 만들기
attach(pr)
jpeg("09.jpg")
plot( x = bodywt # x축 자료
,y = brainwt # y축 자료
,pch = "*" # 점 표시 기호
,xlab = "Body Weight" # x축 라벨
,ylab = "Brain Weight" # y축 라벨
,xlim = c(0,250) # x축 한계
,ylim = c(0,1400) # y축 한계
,sub = "primates") # sub title
dev.off()

jpeg("10.jpg")
plot( x = bodywt # x축 자료
,y = brainwt # y축 자료
,type = "n" # 그래프 타입 표시
,xlab = "Body Weight" # x축 라벨
,ylab = "Brain Weight") # y축 라벨
points(bodywt[brainwt >= 400], brainwt[brainwt >= 400], pch = 3) # 그래프에 포인트 추가하기
points(bodywt[brainwt < 400], brainwt[brainwt < 400], pch = 1) # 그래프에 포인트 추가하기
legend(120, 1000 # 그래프에 레전드 추가하기, 레전드가 들어갈 위치
, c("brain weight <= 400", "brain weight > 400")
, pch=c(3,1))
dev.off()

jpeg("11.jpg")
op = par(mfrow = c(1,2)) # 행 1, 열 2의 레이아웃
plot( bodywt # x축 자료
,brainwt # y축 자료
,xlim = c(0, 300)) # x축 한계
text(x=bodywt, y=brainwt, labels=animal) # 그래프에 텍스트 추가
plot( bodywt # x축 자료
,brainwt # y축 자료
,xlim = c(0, 300)) # x축 한계
text(x=bodywt, y=brainwt, labels=animal, adj=0) # 그래프에 텍스트 추가
par(op) # 레이아웃 끝
dev.off()

# 3.3 그래프 좌표축에 수식 쓰기

p = (1:100)/100 # 자료 생성
jpeg("12.jpg")
plot(p # x 축 자료
,sqrt(p*(1-p)) # y 축 자료
,ylab = expression(sqrt(p(1-p))) # y 축 제목
,type = "b") # 그래프 종류
title("Standard deviation") # 그래프에 제목 넣기
dev.off()

jpeg("13.jpg")
plot(p # x 축 자료
,p*p # y 축 자료
,ylab = expression(p^2) # y 축 라벨(제목)
,type = "l" # 그래프의 종류 line
,las = 1) # 축의 눈금값을 수평으로
dev.off()


# 3.4 다차원 데이터에 대한 다양한 표현

# 3.4.1 얼글 그림

library(aplpack)
data(longley) # 데이터 사용하기
longley # 자료 확인
jpeg("14.jpg")
faces(longley) # Chernoff의 얼굴 그림으로 자료 표시
dev.off()


# 3.4.2 별그림

jpeg("15.jpg")
stars(longley)
dev.off()

# 3.5 lattice 패키지를 이용한 다양한 그래프

data(quakes)
quakes[1:3,]

library(lattice)
mini = min(quakes$depth) # depth 최소값
maxi = max(quakes$depth) # depth 최대값
r = ceiling((maxi-mini)/8) # depth 구간 크기
inf = seq(mini, maxi, r) # 구간 만들기
quakes$depth.cat = factor(floor((quakes$depth - mini)/r),
labels = paste(inf, inf + r, sep = "-")) # 팩터 변수 만들기
jpeg("16.jpg")
xyplot(lat ~ long | depth.cat
, data = quakes
, main = "Fiji earthquakes data") # xy plot
dev.off()

jpeg("17.jpg")
cloud(mag ~ lat * long
, data = quakes
, sub = "magnitude with longitude and lattide") # cloud 3*dim plot
dev.off()

jpeg("18.jpg")
splom(quakes[,1:4]) # scatter plot matrix
dev.off()

jpeg("19.jpg")
bwplot(mag ~ depth.cat
, data = quakes
, main = "깊이 범부에 따른 지진 강도 상자그림") # depth.cat에 따른 상자그림
dev.off()

jpeg("20.jpg")
op = par(mfrow = c(1,2)) #행 1, 열 2의 레이아웃
hist(quakes$mag) # 히스토그램 그래프
hist(quakes$mag, probability = T, main = "histogram with density line")
lines(density(quakes$mag)) # 그래프에 라인 넣기
par(op)
dev.off()


# 예 3.4
data(Orange) # 사용할 데이터 불러오기

jpeg("21.jpg")
xyplot(circumference ~ age | Tree, data = Orange, main = "Orange Tree") # 나무 종류별로 나이(age)에 따른 둘레길이 산점도
dev.off()

jpeg("22.jpg")
histogram(~ circumference | Tree, data = Orange, main = "Orange Tree") # 나무 종류별로 둘레길이에 대한 히스토그램
dev.off()

jpeg("23.jpg")
bwplot(circumference ~ Tree, data = Orange, main = "Orange Tree") # 나무 종류별로 둘레길이에 대한 상자그림
dev.off()

jpeg("24.jpg")
bwplot(age ~ Tree, data = Orange, main = "Orange Tree") # 나무 나이별로 둘레길이에 대한 상자그림
dev.off()

# 3.5.1 산점도 행렬(scatterplot matrix)

data(iris) # 붓꽃 자료인 iris 데이타 사용

attributes(iris) # 속성 확인

library(lattice) # lattice 라이브러리 사용

jpeg("25.jpg")
splom(iris[1:4]) # 1에서 4번째의 변수 사용
dev.off()


# 3.5.2 구름 삼차원 산점도

data(iris) # 붓꽃 자료인 iris 데이타 사용

attributes(iris) # 속성 확인

library(lattice) # lattice 라이브러리 사용

jpeg("26.jpg")
cloud(Sepal.Length ~ Petal.Length * Petal.Width
, data = iris
, main = "iris cloud plot"
, sub = "iris data") # 구름 삼차원 산점도
dev.off()


# 3.5.3 평행선 그림(parallel plot)

data(iris) # 붓꽃 자료인 iris 데이타 사용

attributes(iris) # 속성 확인

library(lattice) # lattice 라이브러리 사용

jpeg("27.jpg")
parallel(~ iris[1:4] | Species, data = iris) # 평행선 그림
dev.off()

# 3.5.4 모자이크 그림(mosaic plot)

library(lattice)

data(HairEyeColor)

jpeg("28.jpg")
mosaicplot(HairEyeColor, shade = T)
dev.off()

# 3.6 3차원 그래프

x1 = seq(-3, 3, length = 50) # -3에서 3까지 50개의 자료 생성
x2 = seq(-4, 4, length = 60) # -4에서 4까지 60개의 자료 생성
f = function(x1, x2) {x1^2 + x2^2 + x1*x2} # 함수 만들기
y = outer(x1, x2, FUN = f) # 외적

jpeg("29.jpg")
persp(x1, x2, y) # perspective plot, 3차원 그림
dev.off()

jpeg("30.jpg")
contour(x1, x2, y) # 등고선 그림
dev.off()

# 3.7 도형 그리기

# 3.7.1 사각형

x = c(1, -1, -1, 1, 1)
y = c(1, 1, -1, -1, 1)

jpeg("30.jpg")
plot(x, y
, type="l" # line
, axes = F # without axes
, xlab = " " # x label
, ylab = " ") # y label
title("Rectangle") # 그래프에 제목 추가하기
dev.off()


# 3.7.2 원

z = seq(0, 2*pi, length = 500)
x = sin(z)
y = cos(z)

jpeg("31.jpg")
plot(x, y
, type = "l" # line
, axes = F # without axes
, xlab = " " # x label
, ylab = " ") # y label
title("Circle") # 그래프에 제목 추가하기
dev.off()

# 3.7.3 나선

z = seq(6*pi, 30*pi, length = 1000)
x = sin(z)/(0.1*z)
y = cos(z)/(0.1*z)

jpeg("32.jpg")
plot(x, y
, type = "l" # line
, axes = F # without axes
, xlab = " " # x label
, ylab = " ") # y label
title("Spiral") # 그래프에 제목 추가하기
dev.off()

































































+ Recent posts