2012-03-31 3 views
6

플롯을 만들 때 어떻게 최대 히스토그램 값을 계산할 수 있습니까?최대 히스토그램 값 계산

주석이있는 플롯에 선을 배치하고 텍스트를 y 축 최대 값에 비례하는 위치에 배치하고자합니다. 예를 들어 :

library(ggplot2) 
df <- data.frame(x = runif(1000)) 


p <- ggplot(data=df, aes(x)) + geom_histogram() 
p + geom_vline(aes(xintercept=0.5),color='red') + geom_text(aes(0.55, 10, label='line'), angle = 90, color='red') 

는 다음과 같은 생산 : 나는이 위치하는 가장 좋은 방법입니다 생각하는 최대 히스토그램 값의 1/3입니다 geom_text()에 인수를 전달하고자하는

enter image description here

텍스트 일관되게,하지만이 count 값을 계산하는 방법을 모르겠습니다.

답변

3

stat_bin은 기본적으로 binwidth = 범위/30을 사용합니다. 나는 그것이 계산 정확히 얼마나 확실하지 않다 그러나 이것은 상당히 합리적인 근사치해야한다 :

max(table(cut(df$x,seq(min(df$x),max(df$x),dist(range(df$x))/30)))) 
+0

1/3로 곱하는 것을 잊지 마세요 :) –

1

일반적으로 간단한 1 차원 최대 찾기 검색은 다음과 같이 구현됩니다 (필자의 경우 ANSI-C).

#include <stdio.h> 
#include <errno.h> 
int printMaxHistValue(int* yValues, int* xValues, int numPoints) { 
    int i, currentY=0, currentX=0, maxX=0, maxY=0, maxIndex=0; 

    if(numPoints <= 0) { 
    printf("Invalid number of points in histogram! Need at least 1 point! Exiting"); 
    return EINVAL; 
    } 


    // Find the values 
    for(i=0; i<numPoints; i++) { 
    currentX = xValues[i]; 
    currentY = yValues[i]; 
    if(currentY > maxY) { 
     maxY = currentY; 
     maxX = currentX; 
     maxIndex = i; 
    } 
    } 

    // Finished with search 
    printf("Found the maximum histogram value of y=%d at bin/x-value of %d (which corresponds to i=%d)",maxY,maxX,maxIndex); 

    // Done 
    return EOK; 
} 

희망이 예 :) 도움이

1

당신은 수를 계산 HIST 기능을 사용할 수 있습니다. geom_histogram과 동일한 저장소 나누기를 전달하십시오. geom_histogram에 binwidth를 제공하지 않는 경우 기본값은/30입니다. geom_histogram이 빈을 생성하는 방법을 살펴보면 다음과 같이 작동합니다.

require(plyr) 
min.brea <- round_any(min(df$x), diff(range(df$x))/30, floor) 
max.brea <- round_any(max(df$x), diff(range(df$x))/30, ceiling) 
breaks <- seq(min.brea, max.brea, diff(range(df$x/30))) 
histdata <- hist(df$x, breaks=breaks, plot=FALSE, right=FALSE) 
max.value <- max(histdata$counts) 

round_any 함수는 plyr에서 온 것입니다.