본문 바로가기

Study/class note

R / 라인 그래프, 산포도 그래프, 상관계수

20 R에서 라인그래프 그리기

시간 순서에 따른 데이터의 변화를 볼 때 유용한 그래프

 

문제141. 아래의 데이터로 plot(점) 그래프를 그리시오

# R
cars <- c(1,3,6,4,9)
cars
plot(cars)
	#dafault type = 'p'

문제142. 위의 그래프에 파란색 선을 그리시오

# R
cars <- c(1,3,6,4,9)
cars
plot(cars, type = 'o', col = 'blue')

type = 'o' : 그래프에 선을 그어라~~ 

plot(cars, type = 'b', col = 'blue')
plot(cars, type = 'l', col = 'blue')
plot(cars, type = 'h', col = 'blue')

type = 'b' / type = 'l' / type = 'h'

문제143. 차와 트럭의 판매 대수를 라인 그래프로 시각화 하시오.

# R
cars <- c(1,3,6,4,9)
trucks <- c(2,5,4,5,12)
plot(cars, type='o', col = 'blue', ylim = c(0,12), axes=FALSE)
lines(trucks, type='o', pch =22, lty=2, col='red')

pch= 21 : 동그라미 / pch = 22 : 네모 / lty = 1 : 직선 / lty = 2 : 점선 

axes = FALSE 는 x축과 y축을 둘 다 지우겠다는 뜻

문제144. 위의 그래프에 가로축, 세로축을 다음과 같이 만드시오.

# R
cars <- c(1,3,6,4,9)
trucks <- c(2,5,4,5,12)
plot(cars, type='o', col = 'blue', ylim = c(0,12), axes = FALSE)
lines(trucks, type='o', pch =22, lty=2, col='red')

axis(1, at = 1:5, lab=c("mon","tue","wed","thu","fri"))  # x축을 그려라라
axis(2)  # y축을 그려라

문제145. 서울지하철 5호선~8호선의 이용현황 시간대별 데이터를 R로 로드하세요.

# R
subway <- read.csv("c:\\data\\5-8호선승하차승객수.csv")
subway

문제146. 지하철 5호선의 승차 인원수로 라인 그래프를 그리시오

(x축을 시간으로 하고 y축을 인원수로 하세요)

# R
subway <- read.csv("c:\\data\\5-8호선승하차승객수.csv")
line_5 <- subway[subway$line_no == '5line', ] 
line_5
plot(line_5$in., type='o', col = 'blue',axes = FALSE, main = '지하철 5호선 승차 인원수')
axis(1, at = 1:20, lab = line_5$time )
axis(2)

문제147. 위의 그래프에 빨간색 점선 직선으로 8호선의 승차 인원수 라인 그래프를 그리시오.

# R
subway <- read.csv("c:\\data\\5-8호선승하차승객수.csv")
line_5 <- subway[subway$line_no == '5line', ] 
line_8 <- subway[subway$line_no == '8line', ]
plot(line_5$in., type='o', col = 'blue', ylim = c(0,70000), axes = FALSE, main = '지하철 5호선,8호선 승하차')
lines(line_8$in., type='o', col = 'red', pch = 22, lty = 2)
axis(1, at = 1:20, lab = line_5$time )
axis(2)

문제148. 위의 그래프에 지하철6호선의 승차 인원수를 green으로 추가하시오.

# R
subway <- read.csv("c:\\data\\5-8호선승하차승객수.csv")
line_5 <- subway[subway$line_no == '5line', ] 
line_8 <- subway[subway$line_no == '8line', ]
line_6 <- subway[subway$line_no == '6line', ]
plot(line_5$in., type='o', col = 'blue', ylim = c(0,70000), axes = FALSE, main = '지하철 5호선,6호선, 8호선 승차 인원수')
lines(line_8$in., type='o', col = 'red', pch = 22, lty = 2)
lines(line_6$in., type='o', col = 'green',pch = 22,lty=2)
axis(1, at = 1:20, lab = line_5$time )
axis(2)

+) 범례(legend) 달기

# R
subway <- read.csv("c:\\data\\5-8호선승하차승객수.csv")
line_5 <- subway[subway$line_no == '5line', ] 
line_8 <- subway[subway$line_no == '8line', ]
line_6 <- subway[subway$line_no == '6line', ]
plot(line_5$in., type='o', col = 'blue', ylim = c(0,70000), axes = FALSE, main = '지하철 5호선,6호선, 8호선 승차 인원수')
lines(line_8$in., type='o', col = 'red', pch = 22, lty = 2)
lines(line_6$in., type='o', col = 'green',pch = 22,lty=2)
axis(1, at = 1:20, lab = line_5$time )
axis(2)
legend("topright", legend = c("5호선","6호선","8호선"), fill = c("blue","green","red"),bg = 'transparent',
       box.lty = 0, cex = 0.8)

box.lty = 0 을 쓰면 레전드의 박스 외곽선을 출력안함

 

21 R에서 산포도그래프 그리기

두 변수간의 관계를 파악할 때 사용하는 그래프

특히 두 변수간의 관계가 양의 관계인지 음의 관계인지를 파악할 때 유용함.

두 데이터(변량) 간의 상관관계 유무를 x,y 평면상에 시각적으로 나타내는 그래프

 

예제. 사원 테이블의 커미션과 월급과의 관계를 산포도 그래프로 그리시오.

# R
emp <- read.csv("c:\\data\\emp2.csv")
plot(emp$comm, emp$al, pch = 21, col = 'red', , bg = 'red')

문제150. 중고차의 주행거리가 높으면 중고차의 가격이 낮아지는지 산포도 그래프로 확인하시오.

# R
usedcar <- read.csv("c:\\data\\usedcars.csv")
usedcar
plot(usedcar$mileage, usedcar$price, pch = 21, col = 'red', bg='red')

문제151. 중고차 주행거리와 가격간의 상관계수를 구하시오.

# R
usedcar <- read.csv("c:\\data\\usedcars.csv")
cor(usedcar$mileage, usedcar$price)

-0.8061494   <- 음의 상관관계를 보이고 있음.

주행거리가 높아질수록 가격이 낮아지는 음의 상관관계를 보이고 있음.

 

문제152. 미국 의료비 데이터로 산포도 그래프를 그리는데 bmi가 높을수록(비만일수록) 의료비가 많이 드는지 확인하시오.

# R
insurance <- read.csv("c:\\data\\insurance.csv")
plot(insurance$bmi, insurance$expenses, pch = 21, col = 'blue', bg = 'blue') # cex = 0.5 점크기 조절
cor(insurance$bmi, insurance$expenses)

상관계수 = 0.1985763

낮은 양의 상관관계를 보이고 있음.

문제153. (오늘의 마지막 문제) 지하철 1~4호선 승하차 승객수.csv를 가지고 라인그래프를 그리시오.

x축을 시간으로 두고, y축을 1,2,3,4 호선으로 해서 색깔을 각각 다르게 하시오(승차인원)

# R
subway <- read.csv("c:\\data\\1-4호선승하차승객수.csv")
head(subway)
line_1 <- subway[subway$line_no == 'line_1', ]
line_2 <- subway[subway$line_no == 'line_2', ]
line_3 <- subway[subway$line_no == 'line_3', ]
line_4 <- subway[subway$line_no == 'line_4', ]
c(max(subway$in.), min(subway$in.))  # 최대값, 최솟값 범위 확인

plot(line_1$in., type='o', col = 'blue', ylim = c(0,5000000),axes = FALSE, main = '지하철 1-4호선 승차 승객수')
lines(line_2$in., type='o', col = 'forestgreen', pch = 22, lty = 1)
lines(line_3$in., type='o', col = 'orange',pch = 22,lty=2)
lines(line_4$in., type='o', col = 'lightblue',lty=2)

y <- seq(0, 5000000, by = 1000000)

axis(1, at = 1:20, lab = line_1$time )
axis(side = 2, at = y)
legend("topright", legend = c("1호선","2호선","3호선","4호선"), fill = c("blue","forestgreen","orange","lightblue"),bg = 'transparent',
       box.lty = 0, cex = 0.8)

+) 참고블로그

https://rfriend.tistory.com/150

 

R 그래프 모수 (Graphical Parameters) : 색깔 (colors), col, col.axis, col.lab, col.main, col.sub, fg, bg

지난번 포스팅에서는 R 그래프 모수(Graphical Parameters)를 설정하는 2가지 방법, 선의 유형(Line Type, lty)과 선의 두께(Line Width, lwd), 기호의 크기(Size of Character, cex) 옵션에 대해서 알아보았습니..

rfriend.tistory.com

https://rvisuall.tistory.com/5

 

[R] 그래프 축 눈금 설정하기

[R] 그래프 축 눈금 설정하기 #1. 주석과 함께 코드 먼저 보기 >코드 #plot을 실행하기 위한 dummy 변수 정의 x_dummy=0 y_dummy=0 #빈 그래프 그리기. type을 n으로, axes는 FALSE로. xlim ylim 이용하여 구간설..

rvisuall.tistory.com

https://rfriend.tistory.com/153

 

R Graphics 낮은 수준의 그래프 함수 (2) XY축 형태 변환 : axis(side, ...)

지난번 포스팅에서는 그래프에 추가적인 정보를 입력하는 낮은 수준의 그래프 함수(low level graphic functions) 중에서 첫번째로 제목, XY축 Label 추가하는 title()에 대해서 알아보았습니다. 이번 포스

rfriend.tistory.com

 

 

반응형