向外移动绘制在曲线上的一系列数字

时间:2017-03-31 05:17:42

标签: r plot

我想知道如何使当前在曲线上绘制的数字向外移动,以便a和{{1}在我的R代码中改变了数字之间的距离和曲线保持不变(即常数)?

请在下图中查看我的R代码:

enter image description here

b

2 个答案:

答案 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)