2014-09-29 45 views
1

的真實平均洽我有一個載體geom_vline平均不與矢量

var = c(5, 3, 6, 0, 1, 1, 1, 0, 4, 2, 1, 3, 3, 6, 3, 15, 1, 0, 2, 3, 
1, 0, 0, 3, 2, 3, 2, 2, 2, 4, 4, 0, 1, 0, 2, 2, 5, 3, 3, 1, 0, 
1, 1, 6, 4, 3, 0, 7, 4, 2, 3, 3, 0, 1, 1, 3, 4, 5, 2, 1, 3, 10, 
13, 3, 1, 4, 5, 3, 1, 1, 5, 4, 2, 1, 6, 1, 2, 3, 5, 8, 3, 1, 
7, 4, 0, 1, 7, 1, 3, 4, 3, 5, 3, 2, 1, 1, 9, 2, 0, 4, 3, 5) 

我使用ggplot和繪圖中位數的垂直線繪製直方圖的分佈。 var的中位數等於3

groupMedian <- median(var) 

print(groupMedian) 

df <- data.table(x = var) 

df <- df[, .N, by=x] 

df$x <- factor(df$x, levels=c(0:25)) 

p <- ggplot(df, aes(x=x, y=N)) + 
    geom_bar(stat="identity", width=1.0, 
    colour = "darkgreen", 
    fill = 'lightslateblue') 

p <- p + labs(title = "Var Histogram", 
      x = "x", 
      y = "Frequency") + 
    scale_x_discrete(drop=FALSE) + 
    geom_vline(xintercept=groupMedian, 
     colour = 'red', size = 2) 

p = p + coord_cartesian(ylim=c(0, 50)) + 
    scale_y_continuous(breaks=seq(0, 50, 2)) 

p = p + theme(panel.grid.major = 
      element_line(colour = "black", linetype = "dotted")) 


ggsave("barplot.png", p, width=8, height=4, dpi=120) 

print(p) 

中值是3,但該行被放置在2

我使用

p = p+ geom_vline(data=var, 
      aes(xintercept = median), 
      colour = 'red', size = 2) 
+2

的問題是,你轉身x軸成的一個因素。 R以索引1開始,而不是0,所以第三個級別的值爲2.這裏是證明:'levels(df $ x)[3]'產生'[1]「2」' – Chase 2014-09-29 20:46:10

+0

@Chase是除了像 geom_vline(xintercept = groupMedian +1) – DataTx 2014-09-29 20:51:56

+0

肯定 - 只是概述了我如何處理這個問題,避免轉換因子。 – Chase 2014-09-29 20:54:10

回答

2

你可以讓還嘗試(使用python numpy的一倍選中) ggplot2代替你爲你做聚合,只是你geom_histogram()。這似乎提供你以後要點:

#load data.table 
library(data.table) 
df <- data.table(x = var) 
groupMedian <- median(var) 

ggplot(df, aes(x)) + 
    geom_histogram(binwidth = 1, 
       colour = "darkgreen", 
       fill = "lightslateblue", 
       origin = -0.5) + #this effectively centers the x-axis under the bins 
    geom_vline(xintercept = groupMedian, 
      colour = "red", 
      size = 2) + 
    scale_x_continuous(breaks = seq(0,25), 
        limits = c(0,25)) 

給你這樣的:

enter image description here

+0

感謝您的建議。我使用前一種方法的原因是因爲當我需要箱子在x軸刻度下居中時。 – DataTx 2014-09-29 20:59:20

+0

@ user5219 - 調整「origin」,請參閱幫助手冊瞭解更多詳情:http://docs.ggplot2.org/current/geom_histogram.html。另外這裏是對此的一般討論:https://groups.google.com/forum/#!topic/ggplot2/hFxDohloTSw。我更新了上面的代碼來反映這一點,但不是圖像。 – Chase 2014-09-29 21:02:59