LoginSignup
14
7

More than 5 years have passed since last update.

ggplot2::geom_spokeで線分(スポーク)を描く

Posted at

見つけたのでメモ。こういうのがさくっと描けます:

fig0-1.png

geom_spokeとは

ある座標点(x, y)から,向き(angle)と半径(radius)を指定することで線分(segment)を描くものです。似たようなものとして,geom_segmentがありますが,こちらは座標の開始点(x, y)と終了点(xend, yend)を指定するのが違いです。

というかgeom_spokeは受け取ったデータのangleとradiusからxendとyendを算出し,GeomSegmentをベースに組み立ててるんだと思います。

使い方

参考ドキュメント

ggplot2の公式サイトにある,以下のドキュメントを参照してください:

Line segments parameterised by location, direction and distance — geom_spoke • ggplot2

また,基本はgeom_segmentなので,そちらのドキュメントも参照するとなおいいかと:

Line segments and curves — geom_segment • ggplot2

基本的な使い方

前準備としてライブラリ読み込みと使うデータを準備

library(dplyr)
library(tidyr)
library(ggplot2)

df <- crossing(x = 1:5, y = 1:4) %>% 
  mutate(angle = runif(20, 0, 2 * pi)) %>% 
  mutate(speed = rnorm(20, 0.4, 0.2) + 0.3) %>% 
  mutate(label = LETTERS[1:20])

では,このデータを使って早速プロットしてみます:

g <- ggplot(df, aes(x, y))

g + geom_spoke(aes(angle = pi, radius = 0.5)) +
   geom_point()

fig1-1.png

このように,aes()でangleとradiusを指定すると,その角度とその半径で線分が描かれます。もちろん変数で指定するのもOKです:

g + geom_spoke(aes(angle = angle, radius = speed)) +
  geom_label(aes(label = label))

fig2-1.png

今回はついでに各開始点にgeom_labelでラベルを重ねました。あと,矢印にもできます:

g + geom_spoke(aes(angle = angle, radius = speed), arrow = arrow()) +
  geom_label(aes(label = label))

fig3-1.png

矢印に関しては,上述したgeom_segmentのドキュメント,もしくは?arrowを参照してください。

応用例

私の方でちょっと遊んでみます。

# データを編集
df2 <- df %>% 
  mutate(x_rnd = rnorm(20, 3, 1)) %>% 
  mutate(y_rnd = rnorm(20, 3, 1)) %>% 
  mutate(group = case_when(
    between(angle, 0, pi/2) ~ "右上",
    between(angle, pi/2, pi) ~ "左上",
    between(angle, pi, pi*3/2) ~ "左下",
    between(angle, pi*3/2, pi*2) ~ "右下"
  ))

# 色々加えてみる
ggplot(df2, aes(x_rnd, y_rnd, group = group)) + 
  geom_spoke(aes(angle = angle, radius = speed, color = group),
                arrow = arrow(length = unit(df2$speed * 0.04, "npc"))) +
  geom_label(aes(label = label, color = group), show.legend = FALSE)

fig4-1.png

このような感じとなります。活用例としては,気象データの風の可視化や,人の動きの可視化など,いろいろあると思います。色々試してみてください。

Enjoy!

14
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
7