2012-04-03 44 views
1

我有這樣垂直50%的行添加到GGPLOT2點圖

qplot(Index, Popularity ,data = data.slopeone.agg) 

創建GGPLOT2點圖表現在我想在所有數據點的一半加上一條垂直線。換句話說,積分是0.5。我想添加這一行來查看這些數據的一部分使得50%。

如何在R中實現這一點?我知道geom_vline,但不知道如何確定vline的位置。

數據結構如下: 每一行都有一個ItemId這個項目的流行度和我的圖表的索引來顯示按受歡迎程度排序的值。

head(data.slopeone.agg) 
    Item Popularity Index 
184 258 0.07695880  1 
29 50 0.07294129  2 
121 181 0.07162558  3 
203 286 0.07030986  4 
225 313 0.06500478  5 
65 100 0.06366796  6 

我的表是這樣的:http://img838.imageshack.us/img838/3194/popt.png

+0

我不知道什麼結構data.slopeone.agg需要。你能包括一個小樣本嗎? – Seth 2012-04-03 16:24:02

+1

也許使用'中值'? – James 2012-04-03 16:26:21

回答

0

的指數現在我發現瞭如何解決我的問題。也許這不是最優雅的方式:

定義一個函數來獲得人氣的數據的50%的垂直線位置

getPopularityVLineIndex = function(popData){ 

    halfPopularity = sum(popData$Popularity)/2 

    # initialize helper variables 
    fiftyPercent = 0; 
    counter = 1; 

    # sum up the popularity values until the half of the sum is reached 
    while (fiftyPercent < halfPopularity) { 
     fiftyPercent = fiftyPercent + popData$Popularity[which(popData$Index == counter)] 
     counter = counter + 1 
    } 

    # the current counter value is the position of the vertical line 
    vLineIndex = counter 

    return (vLineIndex) 
} 

qplot(Index, Popularity ,data = popData) + geom_vline(xintercept = getPopularityVLineIndex(popData), colour="red", linetype = "longdash")) 

如果有人知道一個更優雅的方式,隨意張貼。但也許我的問題現在更容易理解;)

1
p <- qplot(data=data.slopeone.agg, x = Index, y = Popularity) 

現在確定中間流行度值的 「索引」。 請注意,如果有偶數次的觀察值,那麼中位數將無法工作。

attach(data.slopeone.agg) 

得到平均人口觀察

medpop=sort(Popularity)[floor(length(Popularity)/2)] 

獲取價值

lineplace= Index[which(Popularity==medpop)] 
detach(data.slopeone.agg) 

p + geom_vline(xintercept = lineplace) 
+0

'wt'應該是什麼? – 2012-04-03 17:58:06

+0

對不起,我更正了我的答案。我想你想要x變量的中位數,所以'索引'在你的情況。 – Seth 2012-04-03 18:25:59

+0

否@我不希望在指數的50%處有一條線。我想在曲線下面積分是0.5的位置上有一條線。那不是一回事。看看我發佈的圖表圖片 – 2012-04-05 07:06:19