按类别绘制均值和标准差 [英] Plot mean and standard deviation by category

查看:52
本文介绍了按类别绘制均值和标准差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过三个因子水平绘制均值和标准差条形图.

I'm trying to plot a plot with mean and sd bars by three levels of a factor.

(在网上搜索了两个小时,然后查看了 Rbook 和 Rgraphs 的书,我仍然没有找到答案.我认为这是因为这是一个非常简单的问题.)

(After two hours of searching on the internet, then checking the Rbook and Rgraphs book I'm still not finding the answer. I think this is because it is a very simple question.)

我有一个包含三列的简单数据框:my category、mean、sd.

I have a simple data frame with three columns: my categories, mean, sd.

我想用类别平均值及其sd条绘制一个图,就像这个(链接损坏)

I would like to do a plot with the mean by category and its sd bars, just like this one (edit: link broken)

我的数据框看起来像这样

My dataframe looks like this

  color     mean.temp      sd        
  black     37.93431      2.267125        
  red       37.01423      1.852052        
  orange    36.61345      1.339032

我很抱歉问了这个愚蠢的问题,但我真的找不到任何简单的答案来回答我的简单问题.

I'm so sorry for asking this dumb question but I sincerely couldn't find any simple answer to my simple question.

推荐答案

创建一个 data.frame 保存你的数据:

Create a data.frame holding your data:

foo <- data.frame(color=c("black","red","orange"),
    mean.temp=c(37.93431,37.01423,36.61345),
    sd=c(2.267125,1.852052,1.339032))

现在,我们首先将均值绘制为点,确保我们有足够的水平空间 (xlim) 和垂直空间 (ylim),抑制 x 轴注释 (xaxt="n") 和所有轴标签(xlab="", ylab="").

Now, we first plot the means as dots, making sure that we have enough room horizontally (xlim) and vertically (ylim), suppressing x axis annotation (xaxt="n") and all axis labeling (xlab="", ylab="").

plot(1:3,foo$mean.temp,pch=19,xlab="",ylab="",xaxt="n",xlim=c(0.5,3.5),
    ylim=c(min(foo$mean.temp-foo$sd),max((foo$mean.temp+foo$sd))))

接下来,我们将标准偏差绘制为线.您还可以使用三个单独的 lines 命令,这可能更易于阅读.这样,我们首先通过 rbind() 将数据收集到矩阵中.R 会自动将这些矩阵转换为向量并回收它们.NA 在那里,所以我们不会将一行的末尾连接到下一行的开头.(尝试移除 NA,看看会发生什么.)

Next, we plot the standard deviations as lines. You could also use three separate lines commands, which may be easier to read. This way, we first collect the data into matrices via rbind(). R will automatically turn these matrices into vectors and recycle them. The NAs are there so we don't join the end of one line to the beginning of the next one. (Try removing the NAs to see what happens.)

lines(rbind(1:3,1:3,NA),rbind(foo$mean.temp-foo$sd,foo$mean.temp+foo$sd,NA))

最后,注释 x 轴:

axis(side=1,at=1:3,labels=foo$color)

这篇关于按类别绘制均值和标准差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆