23
25

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

データのhistogramと確率密度関数を同時に描きたい

Last updated at Posted at 2015-08-23

Q.

histogramと確率密度関数を同時に描きたいのですが。

A.

縦軸を確率密度にする(確率密度関数にあわせる)場合

以下のように書きます。

OK_example1.R
library(ggplot2)

dens <- density(faithful$waiting)
bw <- diff(range(faithful$waiting))/20

ggplot(faithful, aes(x=waiting)) +
  geom_histogram(aes(y=..density..), binwidth=bw, fill='white', color='black') +
  geom_density(fill='black', alpha=0.3) +
  xlim(range(dens$x))

OK_example1.png

縦軸をcountにする(histogramにあわせる)場合

以下のように書きます。

OK_example2.R
library(ggplot2)

dens <- density(faithful$waiting)
bw <- diff(range(faithful$waiting))/20

ggplot(faithful, aes(x=waiting)) +
  geom_histogram(binwidth=bw, fill='white', color='black') +
  geom_density(eval(bquote(aes(y=..count..*.(bw)))), fill='black', alpha=0.3)+
  xlim(range(dens$x))

bquote.()で囲われたものを除いてquoteする関数です。他の方法としてはsubstituteやEPTイディオム(eval(parse(text=)))を使う方法があるようです。

OK_example2.png

参考資料

http://stackoverflow.com/questions/5688082/ggplot2-overlay-histogram-with-density-curve
http://stackoverflow.com/questions/11404531/r-ggplot2-adding-count-labels-to-histogram-with-density-overlay
http://stackoverflow.com/questions/27661852/adding-a-density-line-to-a-histogram-with-count-data-in-ggplot2

その他、slack@kohskeさんに教えていただきました。

23
25
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
23
25

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?