以下に生成されるように、確率分布のファセット プロット (binwidth=1 の y=..density.. のヒストグラム) があります。
library(ggplot2)
library(sqldf)
data(iris)
#Create Binned(Factor) Versions of Continuous Variables
iris$Sepal.Length = round(iris$Sepal.Length)
iris$Sepal.Width <- cut(iris$Sepal.Width, breaks = 4)
#Plot Probability Distributions of Sepal.Lengths, Separate Plots for Each Width-bin.
p <-ggplot(iris, aes(x=Sepal.Length, y=..density..)) +
geom_histogram(binwidth=1, alpha=0.5, position = 'identity', aes(fill=Species)) +
facet_wrap(~Sepal.Width)
p
各ファセットに要約統計用の geom_text() または geom_label() を追加したいと思います (例: max(density))。
ここでの回答に基づいて、このコードを試しましたが、各ファセットで各ラベルが重ねて印刷された以下のプロットが得られました。
#Create DataFrame for Labels out of ggplot_build() data
ggbuild <- as.data.frame(ggplot_build(p)$data)
label.data = sqldf('select PANEL, max(density) as max_density from ggbuild group by PANEL ')
#Print Faceted Plot with Simple Summary Stat in Each Facet
p + geom_text(data=label.data, aes(x=.5, y=.8, label=paste0('Max Height: ', round(max_density,2))))
「ggplot の呼び出し以外で要約を取得する方が簡単な場合がある」というこの回答に基づいて、以下のコードを試しました。
p + geom_text(aes(x=0, y=.8, label=label.data$max_density))
しかし、それは私に次のエラーをもたらしました:
エラー: 美学は長さ 1 であるか、データ (100) と同じでなければなりません: x、y、ラベル