【发布时间】:2020-11-20 06:59:27
【问题描述】:
我需要找到一种方法,以与参考线本身相同的角度注释参考线。
下面的语句将产生参考线和上面的标签。但是,线的斜率可能会改变,我需要找到一种方法来确保注释始终处于相同的角度。
plot(1:10,1:10)
abline(a=8, b=-1)
text(x=4, y=5, "reference line label", srt=-28)
在 R 中有一种简单的方法吗? 提前致谢
【问题讨论】:
标签: r
我需要找到一种方法,以与参考线本身相同的角度注释参考线。
下面的语句将产生参考线和上面的标签。但是,线的斜率可能会改变,我需要找到一种方法来确保注释始终处于相同的角度。
plot(1:10,1:10)
abline(a=8, b=-1)
text(x=4, y=5, "reference line label", srt=-28)
在 R 中有一种简单的方法吗? 提前致谢
【问题讨论】:
标签: r
一种方法是使用asp 参数设置绘图纵横比,然后使用指定的asp 计算角度:
asp <- 2
plot(1:10,1:10, asp=asp)
abline(a=8, b=-1)
text(x=4, y=5, "reference line label", srt=180/pi*atan(-1*asp))
abline(a=4, b=-2)
text(x=1, y=3, "reference line label", srt=180/pi*atan(-2*asp))
设置不同的asp:
asp <- 0.8
plot(1:10,1:10, asp=asp)
abline(a=8, b=-1)
text(x=4, y=5, "reference line label", srt=180/pi*atan(-1*asp))
abline(a=4, b=-2)
text(x=1, y=3, "reference line label", srt=180/pi*atan(-2*asp))
【讨论】:
@Andrie 回答的附录:不是第一次在绘图中硬编码纵横比以获得相对坐标比例,而是可以使用以下函数恢复当前工作纵横比:
getCurrentAspect <- function() {
uy <- diff(grconvertY(1:2,"user","inches"))
ux <- diff(grconvertX(1:2,"user","inches"))
uy/ux
}
所以你可以创建你的情节:设置asp <- getCurrentAspect();并继续 @Andrie 的其余解决方案。
据我所知,这个函数存在于 R 生态系统的某个地方,但我还没有看到它......
【讨论】:
par("usr") 闲逛了五分钟,但找不到任何有用的东西。
grconvertX is referred 和 where the C routines are defined, there are no similar counterparts or other routines calling these
par('asp') 有点误导——"asp" 不是par() 的一部分(感觉应该是?)。我在par() 中看到的唯一接近的是比较diff(par('usr') * par('plt')) 的第一个和第三个元素
与ggplot2类似的解决方案
data <- data.frame(x = 1:10, y = 1:10)
intercept <- 10
slope <- -1
ggplot(data, aes(x,y)) + geom_point(shape=1) +
geom_abline(intercept = intercept, slope = slope) +
geom_text(x=4, y=5, label="my label", angle=atan(slope)*180/pi)
intercept <- 10
slope <- -2
ggplot(data, aes(x,y)) + geom_point(shape=1) +
geom_abline(intercept = intercept, slope = slope) +
geom_text(x=4, y=5, label="my label", angle=atan(slope)*180/pi)
【讨论】:
.rprofile 中有一个函数可以删除默认的ggplot2 主题,但这里没有其他不同。
ggplot2 的工作示例:
slope<-1.3
asp<-1
p <- ggplot()
p<-p+scale_x_continuous(limits = c(1, 15), expand = c(0, 0))
p<-p+scale_y_continuous(limits = c(-8, 20), expand = c(0, 0))
p<-p+geom_abline(intercept = 0, slope = slope)
p<-p+coord_fixed(asp)
p<-p+annotate("text", label = "reference line label", x = 3.5, y = 5, colour = "red",angle=atan(slope*asp)*180/pi)
p
带角度的文字:
【讨论】: