본문 바로가기

Lecture_Statistics

R로 데이터 시각화 _ ggplot2() _2

그림에 요소 삽입하기

1. 글자 삽입    --> by. geom_text    > 점 대신 글자 삽입 가능함

  • 글자들이 그림 그리는 부분에서 바깥으로 나가 있을 경우에 안 쪽으로 넣어주기 위해 넣는 옵션 정도로 생각하기
  • family "글자체" -> default = 고딕체 / "mono" "serif"_바탕체
  • fontface "서체" -> "bold" & "italic"
  • hjust "글자를 입력하는 위치" -> "left / right / inward / outward
  • vjust "글자를 입력하는 위치" -> "bottom" / "middle" / "top" / "inward" / "outward"
df = data.frame(trt=c("a", "b", "c"), resp=c(1.2, 3.4, 2.5))
ggplot(df, aes(resp, trt))+geom_point()

ggplot(df, aes(resp, trt))+geom_text(aes(label=trt))
##점 대신에 문자를 찍어주는 명령어 , 글자 default = 고딕체

ggplot(df, aes(resp,trt))+geom_text(aes(label=trt), family="mono")


ggplot(df, aes(resp, trt))+geom_point()

 

ggplot(df, aes(x, y))+geom_point()+geom_text(aes(label=text), size=7)
ggplot(df, aes(x, y))+geom_point()+geom_text(aes(label=text), size=7, angle=30)

#각 점마다 크기를 다르게 하고 싶을 때 (aes 안에서 변수 이름으로 size 설정)
ggplot(df, aes(x, y))+geom_point()+geom_text(aes(label=text, size=s))

ggplot(df, aes(x, y))+geom_point()+geom_text(aes(label=text, size=s, angle=a))

## inward 옵션 설명 _ 글자가 밖으로 튀어나갈 때 안 쪽에 넣어주는 옵션 

df <- data.frame(x=c(1, 2, 1, 2, 1.5), y=c(1, 1, 2, 2, 1.5), text=c('bottom-left', 'bottom-right', 'top-left', 'top-right', 'center'), s=c(6, 8, 10, 12, 14), a=c(0, 30, 45, 60, 90))
ggplot(df, aes(x, y))+geom_text(aes(label=text))

ggplot(df, aes(x, y))+geom_text(aes(label=text), vjust='inward', hjust='inward')

## check_overlap

mpg 자료 속 displ, hwy를 x, y로 삼아서 geom_text를 해라! label=model로 해달라!

check_overlap=TRUE은 동일한 위치에 점이 찍히게 될 경우 먼저 찍힌 점만 남기라는 옵션이다

즉, 앞 쪽에 있는 자료만을 남기게 됨

ggplot(mpg, aes(displ, hwy))+geom_text(aes(label=model))

 

 

ggplot(mpg, aes(displ, hwy))+geom_text(aes(label=model), check_overlap = TRUE)+xlim(0,8)

 

2. class에 따라 labeling! _ geom_dl

class라는 label을 붙일 때 점을 피한 최적의 위치에 labeling 해주는 것! (텍스트의 위치를 자동으로 정해준다)

ggplot(mpg, aes(displ, hwy, colour=class))+geom_point()+geom_dl(aes(label=class), method='smart.grid')   #legend를 보여주는 그림
ggplot(mpg, aes(displ, hwy, colour=class))+geom_point(show.legend =FALSE)+geom_dl(aes(label=class), method='smart.grid')
##legend 안 보여주는 그림

 

 

3. 선 / 영역 / 문자 등을 이용해 그림에 주석 달기

1. 선   

--> geom_line( )  : 자료를 x 변수 순서대로 sorting 후 점을 이어준다.

--> geom_path( ) : 자료에 나타난 순서대로 점을 이어준다.

 

#xlab = x axis label 안 보이게 해줘!   & ylab = y axis label 안 보이게 해줘

# labs(x=NULL, y=NULL)  -> 둘다 한 번에 안 보이게 설정

## ggtitle(" ") _ 그림 title 달아주는 함수 

df = data.frame(x=c(6, 2, 12), y=c(4, 8, 12), label=letters[1:3])

p=ggplot(df, aes(x, y, label=label))+labs(x=NULL, y=NULL)
p+geom_line()+geom_text()+ggtitle("line")

 

p+geom_path()+geom_text()+ggtitle("path")  #가진 데이터 순서대로 연결

 

 

2. 영역  1

--> geom_area( )  : geom_line으로 생기는 선과 y=0 사이의 영역

--> geom_polygon( ) :  geom_path()로 생기는 선, 마지막 점과 첫 점을 이어 생기는 선 사이의 영역

--> geom_rect(aes(xmin = , xmax = , ymin = , ymax = )) : x와 y축의 범위로 지정된 네 점를 이어주는 영역

p+geom_point()

 

p+geom_area()

p+geom_polygon()+geom_text(size=5)

p+geom_rect(aes(xmin=5, xmax=6, ymin=6, ymax=10))

 

3. 영역  2

--> geom_vline(xintercept = , linewidth =, linetype = ) : 지정된 위치에 수직선 (x intercept)

--> geom_hline(yintercept = , linewidth = , linetype = ) : 지정된 위치에 수평선  (y intercept)

--> geom_abline(intercept = , slope = , linewidth = , color = , linetype = ) : 지정된 intercept와 slope로 직선 생성

 

## nudge_x = 50 : x=a 라는 수직선에서 글씨를 조금 띄어서 쓰라는 옵션

## 우리가 정한 scale 중 fill이라는 내용을 manual로 바꾸겠다는 의미 -> 전자가 blue, 후자가가 red야!

ggplot(economics)+ geom_rect(aes(xmin=start, xmax=end,ymin=-Inf, ymax=Inf, fill=party), alpha=0.2, data = presidential1)
+geom_vline(aes(xintercept = as.numeric(start)), data=presidential1, colour='grey50', alpha=0.5)
+geom_text(aes(x=start, y=2500, label=name), data=presidential1, size=3, vjust=0, hjust=0, nudge_x=50)
+geom_line(aes(date, unemploy))
+scale_fill_manual(values=c('blue', 'red'))

- 각 대통령의 시작지점마다 vline -> x의 intercept는 숫자니까 date를 numeric으로, data는 presidential1인 것!

- 대통령의 이름을 text로 넣어라! x는 start 시점에, y=2500 위치에! / 글씨의 사이즈 및 위치 조정

 

ggplot(diamonds, aes(carat, price))+geom_point()
ggplot(diamonds, aes(log10(carat), log10(price)))+geom_point()
## 점이 겹쳐져 있는 정도를 보여주는 그림 bin2d (binning을 한다! 자료가 얼마나 모여 있는지를 counting해서 색을 다르게 해서 보여줌)
ggplot(diamonds, aes(log10(carat), log10(price)))+geom_bin2d()+facet_wrap(~cut, nrow=1)
coef(lm(log10(price)~log10(carat), data=diamonds))

mod_coef <- coef(lm(log10(price)~log10(carat), data=diamonds))

ggplot(diamonds, aes(log10(carat), log10(price)))
+geom_bin2d()+geom_abline(intercept=mod_coef[1], slope=mod_coef[2], colour='white', size=1)
+facet_wrap(~cut, nrow=1)

 

  • cut이 좋으면 carat이 작아도 price가 높을 수 있다는 경향을 보여주는 그림.

 

## geom 속 옵션과 ggplot 속 옵션의 차이  _ ggplot에서 설정한 aesthetic mapping은 뒤의 모든 geom에 영향을 주지만, geom 속 옵션은 해당 geom에서만 영향을 미치게 된다.

'Lecture_Statistics' 카테고리의 다른 글

R로 데이터 시각화 _ ggplot2() _3  (1) 2024.10.09
R로 데이터 시각화 _ ggplot2() _1  (1) 2024.10.07
R 프로그래밍 기본  (1) 2024.10.07