19. 데이터의 시각화


r

Overview

R에서 데이터를 그래프로 시각화 하는 방법에 대해 알아본다.

예제 파일1 : R정형데이터처리하기.xlsx
예제 파일2 : 1014Exfile.zip


plot 실습 1

# 산점도 그래프

height <- sort(c(163, 180, 184, 174, 160, 173, 177, 157))
weight <- sort(c(50, 80, 84, 70, 45, 65, 77, 44))

# 2x2 그래프
# mfrow : x by y 배치 옵션
par(mfrow=c(2, 2))

# 각 타입별 그래프 활용
plot(height, weight, type='l')
plot(height, weight, type='o')
plot(height, weight, type='h')
plot(height, weight, type='s')

# pch(plotting character) : 점의 모양(표시 기호), range : 1 ~ 25
# col(color) : 선색상
# cex(character expansion) : 점의 크기
# lwd(line width) : 선의 굵기
plot(height, weight, type = 'o', pch=5)
plot(height, weight, type = 'o', pch=20, col = 'blue')
plot(height, weight, type = 'o', pch=22, col = 'orange', cex = 1.5)
plot(height, weight, type = 'o', pch=24, col = 'green', cex = 2.0, lwd = 3)

# 그래프 배치 초기화
par(mfrow=c(1,1))

plot 실습 2

baseball <- read.csv('kbo.csv')
baseball
str(baseball)
dim(baseball)

par(family = 'D2Coding')

avg <- baseball$AVG
hr <-baseball$HR

# 산점도(scatter plot)
# lab : label
# lim : limit(하한, 상한)
plot(x = avg, y = hr, main = 'scatter plot', xlab = '타율', ylab = '홈런', xlim = c(0.30, 0.38), ylim = c(0, 45))

meanhr <- mean(hr)

# abline : 선 긋기, a : y절편, b : 기울기
abline(a = meanhr, b = 0, col = 'blue')

# plot안에 text 넣어보기
text(x = 0.305, y = meanhr + 2, labels = '홈런 평균', col = 'blue')

meanavg <- mean(avg)

abline(v = meanavg, col = 'pink', lty = 4, lwd = 5)
text(x = meanavg + 0.005, y = 0, labels = '타율 평균', col = 'pink')

colnames(baseball)

R <- baseball$R
RBI <- baseball$RBI

plot(R, RBI, main = 'r and rbi', xlab = 'R', ylab = 'RBI', xlim = c(min(R) - 10, max(R) + 10), ylim = c(min(RBI) - 10, max(RBI + 10)))

meanrbi <- mean(RBI)
abline(a = meanrbi, b = 0, col = 'lightblue')
text(x = 55, y = meanrbi + 5, labels = '평균 RBI')

plot 실습 3

library(reshape2)

par(family = 'D2Coding')

mydata <- read.csv('../R-Programming/R_data/191015/student_subject_score.csv', header = T)
mydata
colnames(mydata)

# 행 ~ 열
# dcast를 통해 data 변환
namesubject <- dcast(mydata, name ~ subject, value.var = 'jumsu')
namesubject

name <- namesubject[1]
name
class(name)

chartdata <- namesubject[2:7]
chartdata
class(chartdata)

# barplot 에는 matrix, vector만 들어올 수 있음
# 형변환 필요 
c1 <- as.matrix(chartdata)

myrow <- nrow(c1)
mycolor <- rainbow(myrow)

# barplot -> beside 값은 옆으로 펼질지에 대한 옵션
barplot(c1, beside = T, main = '과목별 학생 점수', col = mycolor, ylim = c(0, 100))

# t() 함수를 사용한 행렬 전치
# 학생별 과목 점수
c2 <- t(c1)

# 학생 이름도 t()함수를 통해 전치하여 넣음
colnames(c2) <- t(name)
barplot(c2, beside = T, main = '학생별 과목 점수', col = mycolor, ylim = c(0, 100))

namesubject

# 1번째 학생만 그려보기
c3 <- c1[1,]
c3
subject <- colnames(namesubject[2:7])
subject

# legend : 범례 
barplot(c3, beside = T, main = '개인의 과목 점수', col = mycolor, ylim = c(0, 100), legend = subject)


pie(c3, main = '개인의 과목 점수 파이 그래프')

plot 실습 4

data <- read.csv('R_data/191015/야구성적.csv', header = T)
dim(data)
colnames(data)
str(data)

par(family = 'D2Coding', cex = 0.5)

chartdata <- data$연봉대비출루율
chartdata
range(chartdata)

mycolor <- rainbow(50)
xlabel <- data$선수명

barinfo <- barplot(chartdata, main = '연봉 대비 출루율\n밥값 여부 계산', col = mycolor, names.arg = xlabel, las = 2, ylim = c(0, 50))

barinfo

title(ylab = '연봉 대비 출루율', col.lab = 'red')
title(xlab = '선수명', col.lab = 'blue')

aver <- mean(data$연봉대비출루율)

abline(h = aver, col = 'red', lty = 'dotted')

text(x = 3, y = aver + 1, col = 'black', labels = paste(round(aver, 2), '%(평균 출루율)'))

text(x = barinfo * 1.01, y = chartdata + 1, col = 'black', labels = paste(chartdata, '%'))

# 홈런 개수가 평균 홈런 개수보다 많은 선수들의 막대 그래프 
avghr <- mean(data$홈런)
data2 <- data[c('선수명', '홈런')]
library(dplyr)
res <- filter(data2, 홈런 >= avghr)
res
xname <- res$선수명

avginfo <- barplot(res$홈런, main = '평균 홈런 개수보다 많은 선수', col = mycolor, names.arg = xname, las = 2, ylim = c(0, 50))

abline(h = avghr, col = 'blue', lty = 'dotted')

plot 실습 5

# R정형데이터처리하기.xlsx 파일을 이용하여 다음 물음에 답하시오.
library(rJava)
library(xlsx)
library(dplyr)
library(reshape2)
library(stringr)

xencoding <- 'UTF-8'
filename <- 'R_data/old/R정형데이터처리하기.xlsx'

par(family = 'D2Coding')
par(cex = 0.7)
mcolor <- rainbow(10)

# 출장비지급내역 시트
# 교통비와 식비를 이용하여 산점도 그래프 그리기
data1 <- read.xlsx(file = filename, sheetIndex = 2, encoding = xencoding)
data1
class(data1)
xlabel <- data1$사원명
xlabel
tranf <- data1$교통비
food <- data1$식비
tranf
food
range(tranf)
range(food)

plot(tranf, type = 'o', xlab = '사원명', ylab = '비용', col = 'magenta', ylim = c(50000, 200000))
par(new = T)
plot(food, type = 'o', ylab = "", xlab = "", ylim = c(50000, 200000), col = 'cyan')
legend(x = 8, y = 15000, c('교통비', '식비'), cex = 0.7, col = c('magenta', 'cyan'))

# 가전제품1 시트
# 1일 생산량을 이용하여 세로 막대 그래프 그리기
# 
data2 <- read.xlsx(file = filename, sheetIndex = 3, encoding = xencoding)
oneday <- data2$X1일생산량
xlab2 <- data2$제품명
barplot(oneday, xlab = '제품명', ylab = '1일 생산량', names.arg = xlab2, cex.names = 0.7, ylim = c(0, 250), col = mcolor)


# 가전제품1 시트 ~ 가전제품3 시트와 '사사분기.csv' 파일을 이용하여
# 사분기 데이터 프레임(이름 : q_df)을 만드세요.
#
sheets <- seq(3, 5)
q_df <- data.frame()

q4 <- read.csv('R_data/191015/사사분기.csv')
q4
class(q4)

for( onesheet in sheets ){
  print(onesheet)
  dframe <- read.xlsx(file=filename, sheetIndex = onesheet, encoding=xencoding)
  dframe$qu <- paste((onesheet-2), "사분기", sep='')
  q_df <- rbind(q_df, dframe)
}
q4$qu <- '4사분기'
q_df <- rbind(q_df, q4)
colnames(q_df)
q_df
# 이하 문제들은 q_df을 이용
# 각 분기별/제품명의 1일 생산량으로 막대 그래프 그리기
qsub <- dcast(q_df, 제품명 ~ qu, value.var = 'X1일생산량')
qsub

pdn <- qsub[1]
pdn

chartdata <- qsub[2:5]
chartdata

chart1 <- as.matrix(chartdata)
mrow <- nrow(chart1)
barplot(chart1, beside = T, main = '각 분기별 제품의 1일 생산량', col = mcolor, ylim = c(0, 350), legend = qsub$제품명)

# 각 분기별 총 생산량의 평균을 이용하여 pie 그래프 그리기
q_df$총생산량 <- str_replace_all(q_df$총생산량, ',', '')
q_df$총생산량 <- str_trim(q_df$총생산량)
q_df$총생산량 <- as.numeric(q_df$총생산량)

qavg <- q_df %>% group_by(qu) %>% summarise(avg = round(mean(총생산량), 2))
pavg <- qavg$avg
lbls <- qavg$qu
pct <- round(pavg / sum(pavg) * 100)
lbls <- paste(lbls, pct)
lbls <- paste(lbls, '%', sep = "")
pie(qavg$avg, labels = lbls, main = '각 분기별 총 생산량의 평균')

# 불량품 컬럼으로 히스토 그램(breaks=10) 그래프 그리기
q_df
bad <- q_df$불량품

hist(bad, breaks = 10, freq = T)

# 각 분기별 총 생산량을 이용하여 꺽은 선 그래프 그리기
q_df

qua <- q_df$qu
qavg2 <- q_df %>% group_by(qu) %>% summarise(avg = round(mean(총생산량), 2))
avg4 <- qavg2$avg
plot(avg4, type = 'o', ylim = c(8000, 10000), axes = F)
axis(1, at=1:4, labels = c("1사분기", '2사분기', '3사분기', '4사분기'))
axis(2, ylim = c(8000, 10000))

# boxplot 그리기
boxplot(chart1)

# 총생산량, 불량품, 출고량 boxplot
q_df
q_df$출고량 <- gsub(',','', q_df$출고량)
q_df

tot_prod <- q_df$총생산량
bad_prod <- q_df$불량품 * 100
go_prod <- as.numeric(q_df$출고량)

tot_prod
bad_prod
go_prod

mprod <- data.frame(tot = tot_prod, bad = bad_prod, go = go_prod)
mprod
mprod <- as.matrix(mprod)

boxplot(mprod)





© 2019. by RaP0d

Powered by aiden