본문 바로가기

정리/시각화

[R] ggplot에 내가 원하는 point 그리기

728x90

 

1 ggplot에 point 를 추가하는 방법

ggplot 은 r에서 가시화 작업에 자주 등장하는 그래프를 그리는 패키지입니다.

일반적으로 그래프를 그리다 보면, line으로만 그렸을 때 가시성이 떨어지는 종종 발생합니다.

이를 해결하기 위해 그래프 포맷 자체를 바꾼다던지 하는데 지금은 포인트를 추가하는 방법에 대해 설명하고자 합니다.

1.1 point 의 유형

포인트를 추가하는 유형은 두 가지로 나눌 수 있습니다.

첫번째, line과 같이 점을 나타내는 것이죠.

두번째, line과 무관하게 원하는 위치에 점을 그리는 경우입니다.

1.1.1 line에 종속된 point

line과 같이 점을 나타내고자 하는 경우, ggplot 에는 기본적으로 geom_point를 써서 포인트를 추가로 그립니다. #### geom_point 예시 아래처럼 geom_line() 에 geom_point()를 추가해서 값을 나타내는 지점을 강조할 수 있습니다. 참고로 예제는 비트코인 그래프입니다.

# Scatter plot 
sp <- ggplot(y, aes(x=candleDateTimeKst, y=lowPrice)) +geom_line()
sp
sp + geom_point()

### line에 독립적인 point 그래프와 상관없이 원하는 지점에 point 를 그리는 것입니다. 위의 비트코인 가격 기본 그래프에서 특정 지점에 점을 찍어보겠습니다.

1.1.1.1 geom_point

다음은 geom_point 를 활용한 예시 입니다. mapping 파라미터를 이용해 그리시면 됩니다. shape 를 설정하여 point의 형태도 바꿀 수 있습니다. 이를 응용하면 매수 신호 위치에 적용할 수 있겠네요.

sp <- ggplot(y, aes(x=candleDateTimeKst, y=lowPrice)) +geom_line()
sp
sp + geom_point(mapping =aes(x = y$candleDateTimeKst[20], y = y$lowPrice[20]), color="red");
sp + geom_point(mapping =aes(x = y$candleDateTimeKst[20], y = y$lowPrice[20]-100000), color="red", 
                shape=24, fill="red");

1.1.2 [추가] line에 화살표 넣기 (단일, 복수)

특정 지점에 대해 화살표를 넣어 포인트의 위치를 강조 할 수 있습니다. 이를 응용하여 매수 신호의 강도를 표시할 수 있을 거 같네요. #### geom_segment

tgt_point<-13
sp <- ggplot(y, aes(x=candleDateTimeKst, y=lowPrice)) +geom_line()
### 한개 화살표 그리기
sp2<-sp + geom_segment(aes(x = y$candleDateTimeKst[tgt_point], y = y$lowPrice[tgt_point]-400000, 
                      xend = y$candleDateTimeKst[tgt_point], yend = y$lowPrice[tgt_point]-100000), 
                      arrow=arrow(ends='last', length = unit(0.2, "cm")),                  
                      color='red',size=1.2)
sp2+ annotate(geom = "text",
             x = y$candleDateTimeKst[tgt_point],
             y = y$lowPrice[tgt_point]-400000,
             label =round(y$U1.2_V[tgt_point],3),
             colour = "brown",
             alpha = 0.5,size = 3,
             hjust = 0.5,
             vjust = 2)
### 복수개 화살표 그리기
sp + geom_segment(data= df, aes(x =map_x, y = map_y-400000, 
                      xend = map_x, yend = map_y-100000), 
                  arrow=arrow(ends='last', length = unit(0.2, "cm")),
                  color='red',size=1.2)

참고로 hjust 와 vjust 를 가지고 label text의 horizontal vertical 위치를 설정 할 수 있습니다.