2016-12-08 14 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在傳奇中添加了「黑色」作爲第三個物種。爲了避免這種情況,請使用第一個選項。