階段チャートを作る
利益の変動分析を説明するのに投資家説明会などでよく用いられるグラフが俗に階段チャートとかウォーターフォールチャート、滝グラフとも言われる方法で、グラフの左端に、前期の利益、右端に当期の利益を棒グラフで描き、その間に、セグメント別の利益の増減や科目別の増減などを載せて、利益変動の結果と経過がわかるように示すもの。
r-wakalangで相談したら、geom_segment()という関数を、@KDさんに教わった。
economics %>% filter(date > lubridate::ymd("2014-01-01")) %>% mutate(unemploy_next = lag(unemploy, n = 1L, default = NA)) %>% ggplot() + aes(x = date, y = unemploy) + geom_step(size = 1) + geom_segment(aes(xend = date, y = unemploy, yend = unemploy_next), size = 2, color = "orange", na.rm = TRUE)
具体的には、株価や経済指標の時系列の変動のようなデータを、折れ線グラフ(geom_line)ではなく、X軸とY軸とに成分を分けた、geom_step()を使って動きの部分を表現する。
これに、Yの変動成分をgeom_segment()で上書きして強調描画する方法。
やってみたら難しい
- まずは元ネタとなるデータを用意する
AC = c("売上","原価","販売費","営業外","税金") ACC = c("1","2","3","4","5") PL1 = c(1000, -450, -300, 100, -70) PL2 = c(1200, -600, -400, 50, -50) PL = tibble(ACC = ACC, AC = AC, PL1 = PL1, PL2 = PL2) #Origin PL
- 比較損益を算出する(利益は本来はここでは不要)、その他グラフ用データを作る
PL %>% summarize(ACC = "9", AC = "利益", across(contains("PL"), sum)) %>% #利益を計算 add_row(PL,.before = 1) %>% #損益項目を追加 mutate(Diff = PL2 - PL1) -> PL #比較PL PL %>% rownames_to_column() %>% #順序を固定 mutate(cumDiff = cumsum(Diff), lagDiff = lag(cumDiff, n = 1L, default = 0)) -> PL PL
PL %>% #差分の累計 ggplot() + aes(x = rowname, y = cumDiff) + geom_step(size = .3, group = 1, ) + #group = 1はxで分類しないという意味 scale_x_discrete(label = AC) + geom_segment(aes(x = rowname, xend = rowname, yend = cumDiff, y = lagDiff), #arrow = arrow(angle = 5, ends = "last"), size = 3.5, color = "blue") + geom_hline(yintercept = 0) + labs(title = "滝グラフ", subtitle = "やってみたよ", x = "変動要因", y = "損益インパクト", caption = "(^o^)")
その他
そのものズバリの描画パッケージがあった。
geom_waterfall()
waterfallsパッケージ
Rで解析:継続的なデータ表現に便利です「waterfalls」パッケージ
https://www.karada-good.net/analyticsr/r-506/
矢印を描く
二点の変化を矢印で表すときに、geom_segment()のオプションで、arrow()が使える。
以下r-wakalangで教わったこと
df <- read_csv(" id,x1,y1,x2,y2 a,16,7,12,5 b,12,18,25,41 c,20,8,40,19 ") df_long <- df %>% select(x1,y1) %>% bind_rows( df %>% select(x2,y2) %>% dplyr::rename(x1 = x2, y1 = y2) ) df_long |> ggplot(aes(x1, y1)) + geom_point() + geom_segment( aes(x = x1, y = y1, xend = x2, yend = y2), data = df, arrow = arrow()) + geom_label(aes(x=x1, y=y1, label = id),data=df) #始点にラベルをつける
Last updated 2022-08-06 | auditR (c) N.Nawata