情节的意思,用每GGPLOT2 x值数据集的SD(Plot mean and sd of datas

2019-06-27 04:32发布

我有一个数据集,看起来有点像这样:

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

我想输出为情节一样,但不是平滑的曲线,我只是想取均值/ SD值之间的线段为每套x值。 该图应类似于上图,但锯齿,而不是弯曲的。

我想这一点,但它失败了,即使x值不是唯一的:

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

Answer 1:

你可以尝试写一个总结功能的网站,了解有关建议的哈德利韦翰ggplot2 : http://had.co.nz/ggplot2/stat_summary.html 。 运用他的建议对您的代码:

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

这导致了这个图形:



Answer 2:

?stat_summary是你应该看什么。

下面是一个例子

# functions to calculate the upper and lower CI bounds
uci <- function(y,.alpha){mean(y) + qnorm(abs(.alpha)/2) * sd(y)}
lci <- function(y,.alpha){mean(y) - qnorm(abs(.alpha)/2) * sd(y)}
ggplot(a, aes(x=x,y=y))  + stat_summary(fun.y = mean, geom = 'line', colour = 'blue') + 
            stat_summary(fun.y = mean, geom = 'ribbon',fun.ymax = uci, fun.ymin = lci, .alpha = 0.05, alpha = 0.5)



Answer 3:

您可以使用内置的汇总函数的一个mean_sdl 。 的代码如下所示

ggplot(a, aes(x=x,y=y)) + 
 stat_summary(fun.y = 'mean', colour = 'blue', geom = 'line')
 stat_summary(fun.data = 'mean_sdl', geom = 'ribbon', alpha = 0.2)


Answer 4:

使用GGPLOT2 0.9.3.1,以下做了把戏对我来说:

ggplot(a, aes(x=x,y=y)) + geom_point() +
 stat_summary(fun.data = 'mean_sdl', mult = 1, geom = 'smooth')

在“mean_sdl”是Hmisc包的函数“smean.sdl”和MULT变量的实施方案给出了多少标准偏差(上方和下方的平均值)被显示。

有关原有功能的详细信息:

library('Hmisc')
?smean.sdl


文章来源: Plot mean and sd of dataset per x value using ggplot2
标签: r ggplot2