如何在R中的`dotchart`中找到标签的坐标?

时间:2017-06-03 06:26:24

标签: r plot

我想知道我是否能在R中的dotchart中找到标签的坐标(即x,y)(如下图中的蓝色圆圈所示)? / p>

y = rnorm(20)

groups = factor( rep(1:2, times = c(5, 15) ) )

dotchart(y, groups = groups)

enter image description here

更新:我还要问下图中双头箭头之间的y坐标是什么(假设我知道x但是我希望点位于双头箭头之间,那么y是什么,所以我可以把点放在双头箭头之间的区域内):

enter image description here

1 个答案:

答案 0 :(得分:4)

查看dotchart函数,可以看到组标签是使用mtext编写的:

mtext(glabels, side = 2, line = goffset, at = gpos, adj = 0, 
    col = "red", las = 2, cex = 1)

其中gpos是组标签位置的向量,计算公式为:

gpos <- rev(cumsum(rev(tapply(groups, groups, length)) + 2) - 1)

#########
1  2 
23 16

下面我们尝试使用dotcharts打印的组标签的相同位置(和红色)完全打印组标签:

graphics.off()
set.seed(1)
y = rnorm(20)
groups = factor( rep(1:2, times = c(5, 15) ) )
dotchart(y, groups = groups)

glabels <- levels(groups) 
linch <- 0
ginch <- max(strwidth(glabels, "inch"), na.rm = TRUE)
goffset <- 0.4
nmai <- par("mai")
nmai[2L] <- nmai[4L] + max(linch + goffset, ginch) + 0.1
par(mai = nmai)
lheight <- par("csi")
gpos <- rev(cumsum(rev(tapply(groups, groups, length)) + 2) - 1)
ginch <- max(strwidth(glabels, "inch"), na.rm = TRUE)
goffset <- (max(linch + 0.2, ginch, na.rm = TRUE) + 0.1)/lheight
mtext(glabels, side = 2, line = goffset, at = gpos, adj = 0, 
    col = "red", las = 2, cex = 1)

enter image description here

修改
从此link下载dotchart的修改版本,并将其作为mydotchart.r保存在您的工作目录中

然后输入以下代码:

source("mydotchart.r")
set.seed(1)
y = rnorm(20)
groups = factor( rep(1:2, times = c(5, 15) ) )
mydotchart(y, groups = groups)

函数mydotchart.r给出以下输出:

$gpos
 1  2 
23 16 

$linepos
 [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 18 19 20 21 22

其中gpos是组标签的y位置,linepos是水平虚线灰线的y位置矢量。
使用linepos可以计算上述问题中双头箭头之间的位置。

希望它可以帮到你。