2014-09-29 44 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