2016-09-22 154 views
0

我有一個問題(我是R新手,已經花了幾個小時尋找代碼)繪製了以下的中位數。我希望有一個人可以幫助我!繪製R中點的中位數ggplot

TYPE(time)  DV 
    0    1 
    1    2 
    2    4 
    5    6 
    7    7 
    0    1 
    1    2 
    2    3 
    5    6 
    7    7 
    1    2 
    2    4 
    5    6 
    7    7 
    0    1 
    1    2 
    2    5 
    5    7 
    7    8 
    0    1 
    1    1 
    2    4 
    5    6 
    7    7 
    0    1 
    1    2 
    2    3 
    5    6 
    7    7 

我想繪製使用GGplot2繪製y軸(在這種情況下DV)的中位數的中位數和直線。我只爲第一點構建了代碼,並希望在中位數上加上代碼。謝謝!!!

library(ggplus) 
gg1 <- ggplot(dataplot) + 
    geom_point(aes(x=TYPE, y=DV))) 

回答

0

可以計算的DV平均每種類型先,然後用geom_segment畫中的情節線:

library(dplyr) 
library(ggplot) 
df1 <- df %>% group_by(TYPE) %>% mutate(med = median(DV)) 

gg1 <- ggplot(df1) + 
     geom_point(aes(x=TYPE, y=DV)) + 
     geom_segment(aes(x = TYPE-0.5, xend = TYPE+0.5, y = med, yend = med)) 

enter image description here

作爲一個側面說明,一般geom_boxplot()在需要變量的分位數分佈時更常用,您可以這樣做:

ggplot(df, aes(x = TYPE, y = DV, group = TYPE)) + geom_point() + geom_boxplot() 

enter image description here

中值的位置是相同的,因爲我們繪製手動上方。

+0

謝謝你的迴應!我不熟悉dplyr。當我運行'code'df1 <- df %>%group_by(TYPE)%>%mutate(med = median(DV))''/ code'時,它給了我Error in MethodMethod(「group_by_」): 'group_by_ '應用於類「函數」的對象有沒有辦法解決這個問題? – Monklife

+0

不是很確定,試着分離並重新連接你的dplyr包,有時在'dplyr'之後加載其他包時函數會覆蓋問題。 – Psidom

+0

我嘗試了deattaching和reattaching;它不起作用T_T。是否有另一種方法呢? – Monklife