Skip to content

Instantly share code, notes, and snippets.

@messefor
Created January 11, 2017 13:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save messefor/d4aa53adb4630508fe420637014beb9d to your computer and use it in GitHub Desktop.
Save messefor/d4aa53adb4630508fe420637014beb9d to your computer and use it in GitHub Desktop.
ggplot2で同心円状に複数円を描いて、ポイントもプロットする
library(tidyverse)
library(ggrepel)
#-------------------------
# データ作成
#-------------------------
# 円のインデックスとrを指定(r^2が中心からのユークリッド距離)
dist.vec <- c(user1=1, user2=2, user3=3, user4=4)
idx.vec <- names(dist.vec)
# 円の座標を取得する関数
coord <- function(r, idx, length=1000) {
theta <- seq(-pi, pi,length=length)
x <- 1/r * cos(theta)
y <- 1/r * sin(theta)
data.frame(idx=idx, x=x, y=y)
}
# 円を描写用の全座標をdata.frameへ
df.plot <- do.call(rbind, mapply(coord, dist.vec, idx.vec, SIMPLIFY = FALSE))
# 点を描く座標を各円からランダムで取得
set.seed(2)
point.row.nm <-
df.plot %>%
dplyr::group_by(idx) %>%
tibble::rownames_to_column("rownames") %>%
dplyr::summarise(sample_row=sample(rownames,size=1)) %>%
dplyr::select(sample_row) %>%
as.matrix() %>%
as.vector()
df.point <- df.plot[point.row.nm, ]
#-------------------------
# プロット
#-------------------------
point.size <- 3 # 点のサイズ
font.size <- 4 # 文字サイズ
c.line.type <- 2 # 円の線
s.line.type <- 1 # 中心からの線の種類
center.idx <- "center"
# プロット
g <- ggplot(df.plot, aes(x, y,colour=idx)) +
geom_path(linetype=c.line.type,size=0.3) + coord_equal() + # 円を描く
geom_point(data = df.point, aes(x, y, colour=idx),size=point.size) + # 点を描く
geom_text_repel(data = df.point, aes(x, y, label=idx),size=font.size) + # テキスト表示
geom_point(aes(x=0, y=0, colour=center.idx),size=point.size) + # 中心を描く
geom_text(aes(x=0, y=-0.05, label=center.idx, color=center.idx),size=font.size) + # 中心を描く
geom_segment(aes(x=0, y=0, xend=df.point[1,"x"], yend=df.point[1, "y"]),
linetype=s.line.type, color="gray50") # 中心から線をひっぱる
#arrow=arrow(ends = "both",type="closed", length = unit(0.2,"cm"))
print(g)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment