본문 바로가기
Programming/R

R graphics - 막대그림(barplot)

by 휴/Hue 2022. 7. 26.

1. 막대그림(barplot)

기본 데이터셋 car93dml type을 가져왔다.

type을 확인해보면 크기 순의 범주형 데이터이기 때문에 이를 빈도로 바꿔야 막대차트에 사용할 수 있다.

그래서 with를 사용하고, 이걸 tab이라는 변수에 넣는다.

barplot은 막대그림을 그리는 명령어이다. legend는 주석추가

library(MASS)
head(Cars93)
?Cars93

tab <- with(Cars93, table(Type))
barplot(tab, main="type of car", xlab="type", ylab="number of car",col=1:6,
        legend=c('Compact', 'Large', 'Midsize', 'Small', 'Sporty', 'Van'),
        names.arg=c('Compact', 'Large', 'Midsize', 'Small', 'Sporty', 'Van'))

2. Side형 막대그래프

xtabs: 두 테이블의 값을 집계하기.

(예를 들어 type에는 총 6가지, airbags에는 총 3가지 타입이 있는데 이를 집계한다. large 사이즈에서 driver 좌석만 에어백이 있는 차는 몇 개인지 이렇게.)

beside: 막대들을 겹치게 쌓을 건지? true는 겹치지 않겠다는 의미이다.

#SIDE
tab <- with(Cars93, xtabs(~Type+AirBags))
barplot(tab, col=rainbow(6),
        legend=c('Compact', 'Large', 'Midsize', 'Small', 'Sporty', 'Van'),
        xlab = 'AirBags', ylab='Number of Cars', 
        beside=TRUE)

 

 

3. Statcked형[1]

side형에서 beside만 false로 바꿨을 때

#STATCED 1
tab
barplot(tab, col=rainbow(6),
        legend=c('Compact', 'Large', 'Midsize', 'Small', 'Sporty', 'Van'),
        xlab='AirBags', ylab='Number of Cars',
        beside=FALSE)

4.Statcked형[2]

xlim함수는 x축의 영역범위를 지정한다.

위의 그래프와 다르게 x축이 왼쪽으로 가있는데 그 이유는 총 5개의 막대가 들어 갈 공간이 현재 형성되어 있고

그 중에 3개만 나타났기때문.

- xlim = c(0, ncol(tab)+2) -> 0부터 tab에 담긴 컬럼 개수(3개)에서 2만큼을 추가 = 즉 5

- args.legend : 범례의 위치를 조정. 범례는 좌표가 무엇이냐 따라 위치가 달라진다.

x좌표 = ncol(tab)+2 >>> 5

y좌표 = max(colSums(tab)) >>> 3개의 컬럼의 합의 값 중 가장 큰 값 43

bty='n' 범례 테두리 지정여부. n은 안하겠단 뜻이다.

#STATCED 2
barplot(tab, col=rainbow(6),
        legend = c('Compact', 'Large', 'Midsize', 'Small', 'Sporty', 'Van'),
        xlim=c(0, ncol(tab)+2), xlab="Airbags", ylab="Number of Cars",
        args.legend=list(x=ncol(tab)+2,
        y=max(colSums(tab)), bty='n'))

'Programming > R' 카테고리의 다른 글

Jupyter에서 R 사용하기  (0) 2022.10.28
R graphics - density, Q-Q, boxplot  (0) 2022.07.29
R graphics - pie chart  (0) 2022.07.27