答案 0 :(得分:2)
正如其他同事所提到的,这个距离的计算可以由text()
本身来处理。 text()
中用于此目的的最合适的参数之一是pos
。每个R文档pos
有4个整数值,每个值都在4个主要方向中的一个方向上移动文本:请参阅?text
。在这种情况下,3
会产生所需的效果。
因此,以下内容可能会解决问题:
a = 0 ; b = 1
curve( dnorm(x, mean = a, sd = b ), -4, 4, axes = F, ann = F)
xx <- -4:4
yy <- dnorm(xx, mean = a, sd = b)
text(xx, yy, paste(round(yy, 2) ), font = 2, pos = 3 )
答案 1 :(得分:2)
a = 0
b = 1
#Draw curve
curve(dnorm(x, mean = a, sd = b ), -4, 4, axes = F, ann = F)
#Assign curve to 'cc' and determine the length of points on the curve
cc = curve(dnorm(x, mean = a, sd = b ), -4, 4, axes = F, ann = F)
l_cc = length(cc$x)
xx <- -4:4
yy <- dnorm(xx, mean = a, sd = b)
#Find indices of values in cc$x closest ot xx
slope_inds = findInterval(xx, cc$x)
#Calculate approximate slope of cc for each xx
slope = numeric(0)
for (i in 1:length(slope_inds)){
if (slope_inds[i] == 1){
n = 1
}else if (slope_inds[i] == l_cc){
n = l_cc - 1
}else{
n = slope_inds[i]
}
slope[i] = round(diff(cc$y[n:(n+1)])/diff(cc$x[n:(n+1)]), 1)
}
#Assign pos value based on slope of cc. For ~zero slope, put text on top
# For other slopes assign values accordingly
positions = integer(0)
positions[slope == 0] = 3
positions[slope > 0] = 2
positions[slope < 0] = 4
#Write text
points(xx,yy)
text(xx, yy, paste(round(yy, 2) ), font = 2, pos = positions)