我正在尝试编写一个函数,它将生成我认为的真实点图(与克利夫兰品种不同,我需要一个单变量散点图,其中的点堆叠为(几乎)相等的值) 。我已经接近了:
在此图中,您看到的点实际上是小写“o”的旋转文本字符串。这样做是因为如果重新缩放绘图,我需要点间距保持不变。但是,我想要比小写“o”更好的东西,例如,实心点而不是圆圈。如果我可以访问用于标准绘图符号的字体(plot
函数和相关函数中的 pch = 1:25
),就可以完成此操作。然后我可以使用该字体创建一个文本字符串并获得所需的内容。有人知道该怎么做吗?
PS - 不,包含大量垃圾箱的直方图不是可接受的替代品。
最佳答案
我确实找到了一种使用低级图形参数(即“usr”,绘图区域的实际用户坐标和“cxy”,字符大小)来获得所需点图的方法。 recordGraphics()
函数包装了调整图形大小时需要更改的部分。函数如下:
dot.plot = function(x, pch = 16, bins = 50, spacing = 1, xlab, ...) {
if(missing(xlab))
xlab = as.character(substitute(x))
# determine dot positions
inc = diff(pretty(x, n = bins)[1:2])
freq = table(inc * round(x / inc, 0))
xx = rep(as.numeric(names(freq)), freq)
yy = unlist(lapply(freq, seq_len))
# make the order of the dots the same as the order of the data
idx = seq_along(x)
idx[order(x)] = idx
xx = xx[idx]
yy = yy[idx]
# make a blank plot
plot(xx, yy, type = "n", axes = FALSE, xlab = xlab, ylab = "")
# draw scale
axis(1)
ylow = par("usr")[3]
abline(h = ylow) # extend to full width
# draw points and support resizing
recordGraphics({
yinc = 0.5 * spacing * par("cxy")[2]
points(xx, ylow + yinc * (yy - .5), pch = pch, ...)
},
list(),
environment(NULL))
invisible()
}
如果您希望点之间的间隙更紧或更松,则可以使用 spacing
参数。一个例子...
with(iris, dot.plot(Sepal.Length, col = as.numeric(Species)))
这是一个比尝试使用文本更好的解决方案,但也有点可怕,因为您在 recordGraphics
文档中看到了警告
关于r - R 中的点图(与点图相反),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29639891/