본문 바로가기
  • Let's go grab a data
Data/R

[R 기초] 패키지와 그래프

by pub-lican-ai 2016. 3. 6.
반응형

[R 기초] 패키지와 그래프 #plot #barplot #hist #pie #boxplot #stem


패키지 설치, 로딩, 업데이트

> install.packages("Hmisc")

#Hmisc 패키지를 설치함

> library(Hmisc)

#설치된 패키지를 메모리에 올림

> update.packages()

#업데이트가 필요한 패키지들을 검색하여 업데이트


Hmisc 패키지 함수

> par(mfrow=c(1,2))

# plot영역을 분할하여 추가되는 plot을 배치함

> show.col()

# 컬러표

> show.pch()

# 문자표


그래프 그리기 plot()

예시)

> str(Puromycin)

'data.frame': 23 obs. of  3 variables:

 $ conc : num  0.02 0.02 0.06 0.06 0.11 0.11 0.22 0.22 0.56 0.56 ...

 $ rate : num  76 47 97 107 123 139 159 152 191 201 ...

 $ state: Factor w/ 2 levels "treated","untreated": 1 1 1 1 1 1 1 1 1 1 ...

 - attr(*, "reference")= chr "A1.3, p. 269"

# 기본적으로 들어있는 데이터 Puromycin이용

> PuroTrt <- subset(Puromycin,state=="treated")

# subset함수를 이용하여 데이터프레임내 state 항목이 treated인 데이터들만 별도로 저장

> PuroTrt

   conc rate   state

1  0.02   76 treated

2  0.02   47 treated

3  0.06   97 treated

4  0.06  107 treated

5  0.11  123 treated

6  0.11  139 treated

7  0.22  159 treated

8  0.22  152 treated

9  0.56  191 treated

10 0.56  201 treated

11 1.10  207 treated

12 1.10  200 treated


그래프 타입별 plot

> par(mfrow=c(1,3))

> plot(rate~conc, data=PuroTrt, type="p")

#point

> plot(rate~conc, data=PuroTrt, type="l")

#line

> plot(rate~conc, data=PuroTrt, type="b")

#both


그래프 속성 변화 plot

> par(mfrow=c(1,3))

> plot(rate~conc, data=PuroTrt)

> plot(rate~conc, data=PuroTrt,xlab="X축", ylab="y축", cex.lab=1.5, xlim=c(0.0, 1.2),ylim=c(50,250))

# xlab: x축 범례 ylab: y축 범례 cex.lab: x,y축 범례 크기 xlim: x축 값범위 ylim: y축 값범위

> plot(rate~conc, data=PuroTrt,main="산점도", pch=2, col=3, cex=1.5)

# main: 도표 상단 이름 pch : 데이터 나타내는 형태(위 Hmisc패키지의 문자표) col: 데이터 나타내는 컬러(위 Hmisc 패키지의 컬러표) cex: 데이터 나타내는 크기


plot이미지 외부로 저장

- R스튜디오의 plot탭에서 export 사용해도 됨

예시)

> getwd()

#현재 위치에 저장됨

[1] "c:/data/Lecture"

> png("plot.png")

#png함수로 저장될 파일이름 지정하는 그래픽 디바이스 생성

> dev.list()

RStudioGD       png       png 

        2         3         4 

> plot(rate~conc, data=PuroTrt,main="산점도", pch=2, col=3, cex=1.5)

#생성된 그래픽 디바이스를 통해 도표를 이미지로 저장함

> dev.off()

#사용완료한 그래픽 디바이스를 제거

RStudioGD 

        2 


barplot() bar의 높이에 관심

barplot(height, width, space, names.arg, legend.text,beside, axes...)

height: 기둥의 높이, width: 기둥의 폭, space: 기둥간의 간격, names.arg: 기둥 그룹의 이름, legend.text: 기둥의 범례 문자열, beside: 기둥을 위로 쌓을것인지 옆으로 쌓을 것인지, axes 축을 나타냄(T/F) ...


> str(ldeaths)

 Time-Series [1:72] from 1974 to 1980: 3035 2552 2704 2554 2014 ...
#시계열 자료

> ldeaths

      Jan  Feb  Mar  Apr  May  Jun  Jul  Aug  Sep  Oct  Nov  Dec

1974 3035 2552 2704 2554 2014 1655 1721 1524 1596 2074 2199 2512

1975 2933 2889 2938 2497 1870 1726 1607 1545 1396 1787 2076 2837

1976 2787 3891 3179 2011 1636 1580 1489 1300 1356 1653 2013 2823

1977 3102 2294 2385 2444 1748 1554 1498 1361 1346 1564 1640 2293

1978 2815 3137 2679 1969 1870 1633 1529 1366 1357 1570 1535 2491

1979 3084 2605 2573 2143 1693 1504 1461 1354 1333 1492 1781 1915

> ld<-matrix(ldeaths,nrow = 6,byrow = T)

#매트릭스 데이터형으로 변환

> ld

     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]

[1,] 3035 2552 2704 2554 2014 1655 1721 1524 1596  2074  2199  2512

[2,] 2933 2889 2938 2497 1870 1726 1607 1545 1396  1787  2076  2837

[3,] 2787 3891 3179 2011 1636 1580 1489 1300 1356  1653  2013  2823

[4,] 3102 2294 2385 2444 1748 1554 1498 1361 1346  1564  1640  2293

[5,] 2815 3137 2679 1969 1870 1633 1529 1366 1357  1570  1535  2491

[6,] 3084 2605 2573 2143 1693 1504 1461 1354 1333  1492  1781  1915

> month.abb

#월별 영어 약어

 [1] "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec"

> colnames(ld)<-month.abb

#열 이름 지정

> rownames(ld)<-1974:1979

#행 이름 지정

> ld

#이제 원자료와 같아짐 데이터형만 바뀜

           Jan  Feb  Mar  Apr  May  Jun  Jul  Aug  Sep  Oct  Nov  Dec

1974 3035 2552 2704 2554 2014 1655 1721 1524 1596 2074 2199 2512

1975 2933 2889 2938 2497 1870 1726 1607 1545 1396 1787 2076 2837

1976 2787 3891 3179 2011 1636 1580 1489 1300 1356 1653 2013 2823

1977 3102 2294 2385 2444 1748 1554 1498 1361 1346 1564 1640 2293

1978 2815 3137 2679 1969 1870 1633 1529 1366 1357 1570 1535 2491

1979 3084 2605 2573 2143 1693 1504 1461 1354 1333 1492 1781 1915

> str(ld)

 num [1:6, 1:12] 3035 2933 2787 3102 2815 ...

 - attr(*, "dimnames")=List of 2

  ..$ : chr [1:6] "1974" "1975" "1976" "1977" ...

  ..$ : chr [1:12] "Jan" "Feb" "Mar" "Apr" ...

> par(mfrow=c(2,2))

> ld[,"Jan"]

1974 1975 1976 1977 1978 1979 

3035 2933 2787 3102 2815 3084 

> barplot(ld[,"Jan"])

> barplot(ld,beside = T)

> barplot(ld,beside = F)

> barplot(ld,beside = F, horiz = T, density = 5)


파이차트 pie()

예시)

>ld["1977",]

 Jan  Feb  Mar  Apr  May  Jun  Jul  Aug  Sep  Oct  Nov  Dec 

3102 2294 2385 2444 1748 1554 1498 1361 1346 1564 1640 2293 

> sum(ld["1977",])

[1] 23229

> pie(ld["1977",])



히스토그램 hist()

hist(breaks, freq, probability, right,...)

breaks: 기둥의 절단점으로 벡터나 함수, 알고리즘이 들어 갈 수 있음

freq: TRUE-빈도 FALSE-확률

probability: 확률 (전체 면적 대비 면적 비율)

right: TRUE-기둥별 최소값 불포함 최대값 포함

예시)

> head(mtcars)

                   mpg cyl disp  hp drat    wt  qsec vs am gear carb

Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4

Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4

Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1

Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1

Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2

Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1

> str(mtcars)

'data.frame': 32 obs. of  11 variables:

 $ mpg : num  21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...

 $ cyl : num  6 6 4 6 8 6 8 4 4 6 ...

 $ disp: num  160 160 108 258 360 ...

 $ hp  : num  110 110 93 110 175 105 245 62 95 123 ...

 $ drat: num  3.9 3.9 3.85 3.08 3.15 2.76 3.21 3.69 3.92 3.92 ...

 $ wt  : num  2.62 2.88 2.32 3.21 3.44 ...

 $ qsec: num  16.5 17 18.6 19.4 17 ...

 $ vs  : num  0 0 1 1 0 1 0 1 1 1 ...

 $ am  : num  1 1 1 0 0 0 0 0 0 0 ...

 $ gear: num  4 4 4 3 3 3 3 4 4 4 ...

 $ carb: num  4 4 1 1 2 1 4 2 2 4 ...

> mtcars$mpg

 [1] 21.0 21.0 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 17.8 16.4 17.3 15.2 10.4 10.4 14.7 32.4 30.4 33.9 21.5

[22] 15.5 15.2 13.3 19.2 27.3 26.0 30.4 15.8 19.7 15.0 21.4

> par(mfrow=c(2,2))

> hist(mtcars$mpg)

> hist(mtcars$mpg, breaks = 12)

> hist(mtcars$mpg, breaks = 12, freq = F, col=c("red","blue"))

> quantile(mtcars$mpg)

    0%    25%    50%    75%   100% 

10.400 15.425 19.200 22.800 33.900 

> hist(mtcars$mpg, breaks = quantile(mtcars$mpg), freq = F, col=c("red","blue"))



boxplot() 박스

예시)

> boxplot(mtcars$mpg)

> quantile(mtcars$mpg)

    0%    25%    50%    75%   100% 

10.400 15.425 19.200 22.800 33.900 

stem() 줄기 잎

예시)

> stem(mtcars$mpg)


  The decimal point is at the |


  10 | 44

  12 | 3

  14 | 3702258

  16 | 438

  18 | 17227

  20 | 00445

  22 | 88

  24 | 4

  26 | 03

  28 | 

  30 | 44

  32 | 49

# 10.4 10.4를 10을 줄기 .4를 잎으로 표현


> sort(mtcars$mpg)

 [1] 10.4 10.4 13.3 14.3 14.7 15.0 15.2 15.2 15.5 15.8 16.4 17.3 17.8 18.1 18.7 19.2 19.2 19.7 21.0 21.0 21.4

[22] 21.4 21.5 22.8 22.8 24.4 26.0 27.3 30.4 30.4 32.4 33.9


저수준 그래픽함수 : 고수준 그래픽 함수 위에 계속해서 추가해서 처리

추가 업데이트 예정


반응형