如何绘制与平均值的偏差

时间:2015-01-06 20:24:50

标签: r ggplot2 mean

在R中,我创建了一个简单的一列矩阵,产生一个带有集合均值和给定标准差的数字列表。

rnorm2 <- function(n,mean,sd) { mean+sd*scale(rnorm(n)) }
r <- rnorm2(100,4,1)

我现在想绘制这些数字与平均值的差异。我可以在Excel中执行此操作,如下所示:

enter image description here

但是我想使用ggplot2在Excel图表中使用折线图创建一个图表,但是如果我可以将其作为列,那就更好了。我尝试过使用散点图,但我无法弄清楚如何将其转换为与均值的偏差。

3 个答案:

答案 0 :(得分:6)

也许你想要:

rnorm2 <- function(n,mean,sd) { mean+sd*scale(rnorm(n)) }
set.seed(101)
r <- rnorm2(100,4,1)
x <- seq_along(r)  ## sets up a vector from 1 to length(r)
par(las=1,bty="l") ## cosmetic preferences
plot(x, r, col = "green", pch=16) ## draws the points
## if you don't want points at all, use 
##    plot(x, r, type="n")  
## to set up the axes without drawing anything inside them
segments(x0=x, y0=4, x1=x, y1=r, col="green") ## connects them to the mean line
abline(h=4)

如果你在0附近绘图,你可以使用type="h"自动执行此操作:

plot(x,r-4,type="h", col="green")

要在ggplot2中执行此操作:

library("ggplot2")
theme_set(theme_bw()) ## my cosmetic preferences
ggplot(data.frame(x,r))+
    geom_segment(aes(x=x,xend=x,y=mean(r),yend=r),colour="green")+
    geom_hline(yintercept=mean(r))

答案 1 :(得分:3)

Ben使用ggplot2的答案效果很好,但是如果你不想手动调整线宽,你可以这样做:

# Half of Ben's data
rnorm2 <- function(n,mean,sd) { mean+sd*scale(rnorm(n)) }
set.seed(101)
r <- rnorm2(50,4,1)
x <- seq_along(r)  ## sets up a vector from 1 to length(r)

# New variable for the difference between each value and the mean
value <- r - mean(r)

ggplot(data.frame(x, value)) +
  # geom_bar anchors each bar at zero (which is the mean minus the mean)
  geom_bar(aes(x, value), stat = "identity"
           , position = "dodge", fill = "green") +
  # but you can change the y-axis labels with a function, to add the mean back on
  scale_y_continuous(labels = function(x) {x + mean(r)})

enter image description here

答案 2 :(得分:1)

基础R中的

非常简单,只需做

plot(r, col = "green", type = "l")
abline(4, 0)

enter image description here

您还标记了ggplot2,因此在这种情况下它会更复杂一些,因为ggplot需要创建数据框然后将其融合。

library(ggplot2)
library(reshape2)
df <- melt(data.frame(x = 1:100, mean = 4, r = r), 1)
ggplot(df, aes(x, value, color = variable)) +
  geom_line()

enter image description here