0

我有一个概率分布的多面图(y = ..密度..的直方图,binwidth = 1),如下所示。

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,标签

4

0 回答 0