在R中的for循环中绘图
我需要画出柯西分布的对数似然函数。下面是用于计算Cauchy分布的log loikelihood的代码:在R中的for循环中绘图,r,plot,statistics,distribution,R,Plot,Statistics,Distribution,我需要画出柯西分布的对数似然函数。下面是用于计算Cauchy分布的log loikelihood的代码: CauchyLL <- function(theta,x){ #CauchyLL is the log-likelihood function for the Cauch Distribution #x is the data vector and theta is the unknown parameter n <- length(x) #f0 is the l
CauchyLL <- function(theta,x){
#CauchyLL is the log-likelihood function for the Cauch Distribution
#x is the data vector and theta is the unknown parameter
n <- length(x)
#f0 is the log likelihood function
#f1 is the first derivative of the log likelihood
#f2 is the second derivative of the log likelihood
f0 <- -n*log(pi)-sum(log((x-theta)^2+1),na.rm=TRUE)
f1 <- sum((2*(x-theta))/((x-theta)^2+1),na.rm=TRUE)
f2 <- 2*sum(((x-theta)^2-1)/((x-theta)^2+1),na.rm=TRUE)
return(c(f0,f1,f2))
}
这个for循环似乎只绘制最后一个θ值,但它不绘制前19个θ值。我怎样才能改变它,得到所有20个θ值的曲线图
绘图
将“始终”覆盖上一个绘图。唯一的例外是,如果特定的plot
方法支持add=
参数。它不是通用的
一种常见的技术(使用基本图形时)通常是第一次调用plot
,然后为每个后续添加调用相应的函数(例如,点(…)
或行(…)
,还有许多其他功能可用)。由于您可能并不总是知道如何在第一次使用初始的绘图构建画布(您不知道完整的维度),因此可能更有用的方法是先计算所有数据,然后确定xlim
和ylim
,然后从“空画布”开始,例如:
plot(NA,type=“n”,main=“qux!”,
xlim=my_xs,xlab=“Theta”,ylim=my_ys,ylab=“Cauchy”)
点(xgrid,mydat[1,])#等
#或许
(rn为1:10)点(xgrid[rn],mydat[rn])
CauchyLL
函数来处理theta
向量确实是可行的,但这里有一个权宜之计:
sapply(xgrid,CauchyLL,x)
# [,1] [,2] [,3] [,4] [,5] [,6]
# [1,] -119.527861 -115.986843 -111.869287 -107.015480 -101.159610 -93.873188
# [2,] 3.288293 3.809062 4.452029 5.298709 6.484735 8.175297
# [3,] 39.002874 38.805443 38.451129 37.815442 36.552463 33.531193
# [,7] [,8] [,9] [,10] [,11] [,12]
# [1,] -84.893042 -77.253757 -73.733690 -72.9736583 -74.294976 -74.6098028
# [2,] 9.342616 5.359918 1.921416 -0.6010282 -1.108758 0.2153465
# [3,] 25.228194 17.802691 18.071895 19.4391628 24.863162 23.7244631
# [,13] [,14] [,15] [,16] [,17] [,18]
# [1,] -74.4040007 -77.690581 -86.359895 -95.35868 -102.600671 -108.487314
# [2,] -0.5162973 -6.556115 -9.660541 -8.09967 -6.478883 -5.363464
# [3,] 17.5721616 16.121772 26.837379 34.13162 36.802884 37.967104
# [,19] [,20]
# [1,] -113.436160 -117.707625
# [2,] -4.576469 -3.993343
# [3,] 38.578288 38.941769
我推断您只对第一行感兴趣(基于plot函数中的[1]
),因此我将从中获取第一行,并在一个命令中全部绘制:
plot(xgrid,sappy(xgrid,CauchyLL,x)[1,]
x <- c(1.77, -0.23, 2.76, 3.80, 3.47, 56.75, -1.34, 4.24, -2.44, 3.29, 3.71, -2.40, 4.53, -0.07, -1.05, -13.87, -2.53, -1.75, 0.27, 43.21)
xgrid<-seq(-9,10,by=1)
for(j in 1:20){
print(xgrid[j])
print(CauchyLL(xgrid[j],x)[1])
plot(xgrid[j],CauchyLL(xgrid[j],x)[1])
}