[ggplot] 2차원 그래프

몇 가지 데이터가 있어서 점을 찍어보고 싶다. 그리고 눈에 확 들어오게 점이 몰려 있는 곳도 잘 표시하고자 한다. 이러한 목적을 달성할 때 {ggplot2}가 좋다.

우선 기본적인 그림을 그려보자.

require(ggplot2)
require(gcookbook)

draw_my_graph <- function() {
  g <- ggplot(faithful,
              aes(x=eruptions,y=waiting))
  g + geom_point()
}

실행은
> draw_my_graph()

그 결과는 다음과 같다.


눈으로 봐도 잘 보이기는 하지만 다음과 같이 하면 더 잘 보인다.


draw_my_graph_density <- function() {
  g <- ggplot(faithful,aes(x=eruptions,y=waiting))
  g <- g + geom_point()
  g <- g + stat_density2d(aes(
    alpha=..density..),
    geom='tile',
    contour=FALSE)
  g
}

실행을
> draw_my_graph_density()

결과는


너무 칙칙한가?

> draw_my_graph_density2() + theme_classic()



선택할 수 있는 theme은 이것 이외에도 많다.

theme_gray()
theme_bw()
theme_linedraw()
theme_light()
theme_minimal()

논문이나 보고서에 넣기에는 폰트도 예쁘지 않고 크기도 작다. 바꿔보자.

> draw_my_graph_density2() + theme_classic(base_family="serif",base_size=30)

아직도 몇 가지 문제가 있다.
축의 라벨이 소문자로 시작하고 있다. 대문자로 고치자.
그리고 density 값이 중요한 것이 아니고 그냥 표현만 한 것이다. 거슬리는 범례 따위 없애자.

draw_my_graph_density3 <- function() {
  g <- ggplot(faithful,aes(x=eruptions,y=waiting))
  g <- g + geom_point()
  g <- g + stat_density2d(aes(
    alpha=..density..),
    geom='tile',
    contour=FALSE)
  g <- g + scale_alpha_continuous(range=c(0,0.5))
  g <- g + theme_classic(
    base_family='serif',
    base_size=20)
  g <- g + theme(legend.position='none') #범례 지우기
  g <- g + xlab("Eruptions") + ylab("Waiting")
  g
}

실행은

> draw_my_graph_density3()

결과는 다음과 같다.


여러 그래프에 같은 형식의 theme을 적용하려면 귀찮으니까 함수로 빼는 것도 요령.

my_theme <- function(g) {
  mt <- g + theme_classic(base_family='serif',base_size=20)
  mt <- mt + theme(legend.position='none')
  mt
}
my_label <- function(g) {
  ml <- g+ xlab("Eruptions")
  ml <- ml + ylab("Waiting")
  ml
}

draw_my_graph_density4 <- function() {
  g <- ggplot(faithful,aes(x=eruptions,y=waiting))
  g <- g + geom_point()
  g <- g + stat_density2d(aes(
    alpha=..density..),
    geom='tile',
    contour=FALSE)
  g <- g + scale_alpha_continuous(range=c(0,0.5))
  # 모양을 꾸미기
  g <- my_theme(g)
  g <- my_label(g)
  g
}

참고: R Graphics Cookbook by W. Chang

댓글

이 블로그의 인기 게시물

R에서 csv 파일 읽는 법

xlwings tutorial - 데이터 계산하여 붙여 넣기