본문 바로가기
  • plotly로 바로쓰는 동적시각화 in R & 파이썬
Plotly in R - 그래프에 마우스를 올려봅시다

plotly의 spikemode in R

by 아참형인간 2022. 11. 26.
spikemode.knit

사용데이터 : https://2stndard.tistory.com/68

스파이크 모드(spikemode)

plotly에서는 스파이크라인이라는 보조선을 지원한다. 스파이크 라인은 마우스 포인팅에서부터 X축, Y축으로의 안내선을 의미한다. 이 안내선을 사요하여 해당 마우스 포인트가 현재 어떤 값을 가리키고 있는지를 쉽게 알수 있다. 이 스파이크의 설정은 xaxis, yaxis의 하위 속성으로 ‘spikemode’ 속성을 사용하여 설정할 수 있다. 따라서 한 축으로부터의 스파이크 라인을 만들수도 있고 X, Y축 모두의 스파이크 라인을 만들수도 있다. 스파이크 라인은 항상 나타나는 것이 아니고 호버가 나타날 경우 발생된다. 따라서 ‘hovermode’가 ’closet’ 일경우는 마우스 포인터가 트레이스를 가리킬 때 나타나고 호버모드가 ‘x’, ‘y’나 ’x unified’, ‘y unified’일 경우는 항상 나타난다. ’spikemode’는 ’across’, ‘tozero’, ‘marker’의 세 가지 속성값을 가지는데 이들은’+’를 사용하여 서로 중첩하여 사용할 수 있다.

acorss

’spikemode’의 ’across’는 X축이나 Y축의 값에 대해 전체 플롯을 가로지르는 스파이크 라인을 만든다.

total_deaths_5_nations_by_day <- df_covid19 |> 
  filter((iso_code %in% c('KOR', 'USA', 'JPN', 'GBR', 'FRA'))) |>
  filter(!is.na(total_deaths_per_million))

total_deaths_5_nations_by_day |>
  ## plotly 객체 생성
  plot_ly() |>
  add_trace(type = 'scatter', mode = 'lines', 
            x = ~date, y = ~total_deaths_per_million , linetype = ~location, connectgaps = T) |>
  layout(title = '코로나 19 사망자수 추세', 
         xaxis = list(title = '', spikemode = 'across'), 
         yaxis = list(title = '10만명당 사망자수 누계', spikemode = 'across'), 
         margin = margins, 
         hovermode = 'closet', 
         hoverdistance = 5)

tozero

’spikemode’의 ’tozero’는 X축이나 Y축의 0에서부터(zeroline) 마우스 포인터에 해당하는 트레이스까지의 스파이크 라인을 만들어준다.

total_deaths_5_nations_by_day |>
  ## plotly 객체 생성
  plot_ly() |>
  add_trace(type = 'scatter', mode = 'lines', 
            x = ~date, y = ~total_deaths_per_million , linetype = ~location, connectgaps = T) |>
  layout(title = '코로나 19 사망자수 추세', 
         xaxis = list(title = '', spikemode = 'tozero'), 
         yaxis = list(title = '10만명당 사망자수 누계', spikemode = 'tozero'), 
         margin = margins, 
         hovermode = 'closet', 
         hoverdistance = 5)

marker

’spikemode’의 ’marker’는 X축이나 Y축위에 마커를 표시하고 해당 데이터를 표시하는 방법이다. 이 방법은 선이 나타나지는 않고 축위에 포인팅만이 나타난다.

total_deaths_5_nations_by_day |>
  ## plotly 객체 생성
  plot_ly() |>
  add_trace(type = 'scatter', mode = 'lines', 
            x = ~date, y = ~total_deaths_per_million , linetype = ~location, connectgaps = T) |>
  layout(title = '코로나 19 사망자수 추세', 
         xaxis = list(title = '', spikemode = 'marker'), 
         yaxis = list(title = '10만명당 사망자수 누계', spikemode = 'marker'), 
         margin = margins, 
         hovermode = 'closet', 
         hoverdistance = 5)

댓글