2016-12-08 7 views
0

答えがhereのように思えますが、私が必要な場所に移動する必要がありますが、それを適用しようとしたときにエラーをデバッグするのに問題があります。2つのヒストグラム分布のggplotで1つのクロップド・カラムにラベルを付ける

2つのディストリビューションを一緒に描画し、そのうちの1つのディストリビューションのうち最も高いバーを切り抜くために「ズームイン」するコードがあります(うまくいきます)。これまでのところ

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

とても良いです。オブジェクトの種は 'が見つかりません:私はエラーにevalの中

エラー(exprの、ENVIR、enclos)を取得トリミングされたバーの真の高さ

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

に注釈を付けるには、以下のコードを追加する場合を除き、

ここ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の出力がありますあなたはggplot()ステートメントで美学fillをSpeciesにグローバルに定義したことです。テキストgeomを追加すると、ggplotは2番目のデータフレームに存在しない塗りつぶし色を判別するために "Species"を探しています。次の2つの方法でこれを解決することができ

: はgeom_histogramステートメントにggplotの文からfill=Speciesを移動し、次のいずれか

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

編集:上記の画像は、2番目のオプションを使用して作成されました。ご覧のように、ggplotは伝説の第3の種として "black"を追加しました。これを避けるには、最初のオプションを使用します。

関連する問題