在 2 个直方图分布的 ggplot 中标记单个裁剪列

Labeling a Single Cropped Column in ggplot of 2 Histogram Distributions

答案 似乎应该让我到达我想要的位置,但我在尝试应用它时遇到调试错误的问题。

这里有一些代码(工作正常)将两个分布绘制在一起,'zoom in' 裁剪其中一个分布的最高条。

data(iris)

#Round Sepal.Length for Binning 
iris$Sepal.Length = round(iris$Sepal.Length)

#Drop versicolor rows so density plot comes out skewed like my data
iris <- iris[iris$Species!="versicolor",]

#Plot density plot, truncating 0.8 column at (setosa, 5) 
p <-ggplot(iris, aes(x=Sepal.Length, y=..density.., fill=Species)) +
  geom_histogram(binwidth=1, alpha=0.5, position = 'identity') +
  coord_cartesian(ylim = c(0, 0.6)) 

p

到目前为止一切顺利。除非我添加下面的代码来注释裁剪栏的真实高度

p + geom_text(data=as.data.frame(ggplot_build(p)$data), 
              aes(x=5, y=0.5, label = paste0("Bar Height: ", max(density))))

我收到错误

Error in eval(expr, envir, enclos) : object 'Species' not found

这是as.data.frame(ggplot_build(p)$data)$density

的输出
0.10 0.80 0.10 0.00 0.00 0.00 0.02 0.54 0.32 0.12

问题是您在 ggplot() 语句中将美学 fill 定义为全局物种。当您添加文本 geom 时,ggplot 正在寻找“物种”来确定填充颜色,这在第二个数据框中不存在。

您可以通过两种方式解决此问题: 将 fill=Speciesggplot 语句移动到 geom_histogram 语句:

p <-ggplot(iris, aes(x=Sepal.Length, y=..density..)) +
geom_histogram(binwidth=1, alpha=0.5, position = 'identity', aes(fill=Species)) +
coord_cartesian(ylim = c(0, 0.6))

或在 geom_text 调用中覆盖填充美学:

p + geom_text(data=as.data.frame(ggplot_build(p)$data), 
          aes(x=5, y=0.5, fill='black', label = paste0("Bar Height: ", max(density))))

编辑: 上图是使用第二个选项制作的。如您所见,ggplot 在图例中添加了“黑色”作为第三种。为避免这种情况,请使用第一个选项。