2016-12-08 11 views
0

答案here似乎应该让我到我想要的位置,但我在尝试应用它时调试错误时遇到问题。在2个直方图分布的ggplot中标记单个裁剪列

下面是一些代码(可以正常工作)将两个分布绘制在一起,然后“放大”以裁剪其中一个分布的最高柱。

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 

enter image description here

到目前为止好。除了当我添加下面的代码注释裁剪酒吧

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

我得到的错误

错误EVAL的真实高度(表达式,ENVIR,enclos):对象“种”未找到

这里是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 
+0

似乎与[this]类似(http://stackoverflow.com/questions/12629647/adding-geom-path-and-geom-text-to-the-same-ggplot-generates-error-in- R) – Haboryme

回答

2

的proble输出m是您在ggplot()声明中将审美fill定义为全局物种。当您添加文本几何时,ggplot正在查找“种类”以确定填充颜色,该颜色在第二个数据框中不存在。

您可以通过两种方式解决这个问题: 无论是从ggplot声明移动fill=Speciesgeom_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)))) 

enter image description here

编辑:上面的图片是使用第二个选项生成的。正如你所看到的,ggplot在传奇中添加了“黑色”作为第三个物种。为了避免这种情况,请使用第一个选项。