2012-03-31 21 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は、デフォルトではビン幅=レンジ/ 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を指定しない場合、デフォルトはrange/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からです。

関連する問題