【问题标题】:How to plot deviation from mean如何绘制与平均值的偏差
【发布时间】:2015-03-04 14:10:31
【问题描述】:

在 R 中,我创建了一个包含一列的简单矩阵,该矩阵产生一个具有设定平均值和给定标准偏差的数字列表。

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

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

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

【问题讨论】:

  • 您所说的“将其作为列”是什么意思?
  • 不是像折线图中那样将每个点连接到前一个和后一个点(对于放大版本,请参见下面的答案),但是有一条线将每个点连接到平均值价值。基本上是一个以均值而不是零为中心的窄条形图

标签: r ggplot2 mean


【解决方案1】:

也许你想要:

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))

【讨论】:

  • 这与我正在寻找的非常接近。你知道我怎样才能去掉这个圈子吗?我可以看到 pch 没有选项只会留下列并有一个透明点
  • type="n" 怎么样(完全省略 pch)?
  • 也可以在末尾添加+ geom_abline(intercept = 4, slope = 0)
  • 这非常完美,最后一个问题:纯粹出于美学原因,我是否能够更改段(列)的宽度,使其成为一个连续的颜色而不是空白。感谢您的所有帮助
  • width = 4 必须手动调整图表的大小和类别的数量。 geom_bar(aes(x, r - mean(r)), stat = "identity", position = "dodge", fill = "green") 的自动版本怎么样?
【解决方案2】:

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)})

【讨论】:

    【解决方案3】:

    在基础 R 中,这很简单,只要做就行了

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

    您还标记了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()
    

    【讨论】:

    • 这很接近,但我优先寻找柱形图,如下面的答案所示,而不是折线图
    • 我想,为简单起见,您可以缩放它并使用type = "h",类似plot(r - 4, col = "green", type = "h") ; abline(0, 0) 之类的快捷方式
    最近更新 更多