使用ggplot2绘制每个x值数据集的均值和sd [英] Plot mean and sd of dataset per x value using ggplot2

查看:1063
本文介绍了使用ggplot2绘制每个x值数据集的均值和sd的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  a<  -  data.frame(x = rep( c(1,2,3,5,7,10,15,20),5),
y = rnorm(40,sd = 2)+ rep(c(4,3.5,3,2.5,2, (a,aes(x = x,y = y))+ geom_point()+ geom_smooth()
ggplot pre>



我需要与该图相同的输出,但我不想使用平滑曲线,而只是在每组x值的平均值/ sd值之间绘制线段。这个图应该看起来类似于上面的图,但是锯齿状,而不是弯曲的。



我试过了,但它失败了,即使x值不是唯一的:

  ggplot(aes aes(x = x,y = y))+ geom_point()+ stat_smooth(aes(group = x,y = y,x = x))
geom_smooth:每个组只有一个唯一的x值。也许你想要aes(group = 1)?


解决方案

您可以尝试编写哈德利Wickham在 ggplot2 网站上: http: //had.co.nz/ggplot2/stat_summary.html 。将您的建议应用到您的代码中:

pre pre $ p $($ x $ y $ data $ a

stat_sum_df < - 函数(fun,geom =crossbar,...){
stat_summary(fun.data = fun,color =blue,geom = geom,width = 0.2,.. 。)
}

p + stat_sum_df(mean_cl_normal,geom =smooth)

结果如下:


I have a dataset that looks a little like this:

a <- data.frame(x=rep(c(1,2,3,5,7,10,15,20), 5),
                y=rnorm(40, sd=2) + rep(c(4,3.5,3,2.5,2,1.5,1,0.5), 5))
ggplot(a, aes(x=x,y=y)) + geom_point() +geom_smooth()

I want the same output as that plot, but instead of smooth curve, I just want to take line segments between the mean/sd values for each set of x values. The graph should look similar to the above graph, but jagged, instead of curved.

I tried this, but it fails, even though the x values aren't unique:

ggplot(a, aes(x=x,y=y)) + geom_point() +stat_smooth(aes(group=x, y=y, x=x))
geom_smooth: Only one unique x value each group.Maybe you want aes(group = 1)?

解决方案

You could try writing a summary function as suggested by Hadley Wickham on the website for ggplot2: http://had.co.nz/ggplot2/stat_summary.html. Applying his suggestion to your code:

p <- qplot(x, y, data=a)

stat_sum_df <- function(fun, geom="crossbar", ...) { 
 stat_summary(fun.data=fun, colour="blue", geom=geom, width=0.2, ...) 
} 

p + stat_sum_df("mean_cl_normal", geom = "smooth") 

This results in this graphic:

这篇关于使用ggplot2绘制每个x值数据集的均值和sd的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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