2016-12-08 4 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)))) 

내가 평가에서 오류를

오류 자른 바의 진정한 높이에 주석을 제외하고 (EXPR, 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

[이]와 유사하게 보입니다. (http://stackoverflow.com/questions/12629647/adding-geom-path-and-geom-text-to-the-same-ggplot-generates-error-in- 아르 자형) – Haboryme

답변

2

proble의 출력의 당신이 성명서에서 미학 fill을 종 (Species)으로 정의했다는 것입니다. 텍스트 기하 구조를 추가하면 ggplot은 두 번째 데이터 프레임에없는 채우기 색상을 결정하기 위해 "Species"를 찾습니다. 을 어느 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

편집 : 위 사진은 두 번째 옵션을 사용하여 제작되었습니다. 보시다시피, ggplot은 전설에서 세 번째 종으로 "검은 색"을 추가했습니다. 이를 방지하려면 첫 번째 옵션을 사용하십시오.