LoginSignup
8
4

More than 1 year has passed since last update.

ggplot2のヒストグラムに累積比率を重ねる

Last updated at Posted at 2018-08-20

(2022-05-06追記) 一時変数を使用しない + グループ別の集計に対応した方法を書いた: ggplot2でヒストグラムに経験分布を重ねて描く - もうカツ丼はいいよな

stat_bin()内部で..count..をゴニョゴニョしつつ値を保持しておき、第2軸の描画に保持した値を流用するとそれっぽい感じに。

library(ggplot2)
bins <- 30
ggplot(diamonds, aes(carat)) +
  geom_histogram(bins = bins) +
  stat_bin(aes(y = cumsum(cnt <<- ..count..) / sum(..count..) * max(..count..)), 
           geom = "line", bins = bins) +
  scale_y_continuous(sec.axis = sec_axis(~ . / max(cnt) * 100, name = "Cumulative percentage[%]"))

image.png

(グローバル環境にオブジェクト作ってしまうのがどうも気持ち悪い…もっと良い方法はないだろうか…。)

参考になりました

8
4
1

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
8
4