R语言与医学统计图形-【22】ggplot2统计变换函数

ggplot2绘图系统——统计变换函数

在几何对象中以参数stat形式出现。

不同的几何对象对应不同的统计变换函数。
image.png
以直方图为例,几何对象geom_histogram(..., stat='bin')stat_bin(.., stat='bar')的作用是一样的。

一般而言,我们不需要对数据进行额外的统计变换,使用默认的就好。但特殊情况时需要用到,如对数据进行log转换。

绘制QQ图

df <- data.frame(y=rt(200,df=5)) #随机生成t分布
ggplot(df,aes(sample=y))+
  stat_qq() #or geom_qq()

image.png

自定义统计变换函数

可通过stat_function自定义一些统计变换函数来绘图,如正弦曲线、正态分布曲线等。

a <- ggplot(data.frame(x=c(-5,5)),aes(x))+
  stat_function(fun=dnorm) #传入的函数只需名字,无需括号

b <- ggplot(data.frame(x=c(-5,5)),aes(x))+
  stat_function(fun=dnorm,args = list(mean=2,sd=.5)) #传参

grid.arrange(a,b,ncol=1)

image.png

同时定义两个额外的统计变换,并进行图层叠加。

f <- ggplot(data.frame(x=c(0,10)),aes(x))
f+stat_function(fun=sin,color='red')+
  stat_function(fun=cos,color='blue')

image.png

自定义函数

test <- function(x){x^2+x+20}
f+stat_function(fun=test)+
  geom_text(aes(x=5,y=75),
            label='y == x ^ 2 + x + 20',
            parse = T,
            size=7)

image.png

自定义统计变换函数能很好地体现出ggplot2的扩展性,自由正是ggplot2的最大优势!

原文地址:https://www.cnblogs.com/jessepeng/p/12307781.html