gpt4 book ai didi

r - 堆栈点一个在另一个之上

转载 作者:行者123 更新时间:2023-12-04 01:56:58 25 4
gpt4 key购买 nike

为了防止过度绘制,我想要一种抖动的替代方法,它只是将一个点堆叠在平均值周围的另一个顶部(通过给定数量的增量垂直偏移它们,而不是像抖动那样添加随机值)。

由此:

example <- data.frame(x=c(1,1,1,2,2,2,2), y=c(1,1,1,2,2,2,2))

qplot(data=example,x=x, y=y)

我想要的是这样的:

example image

这应该可以通过 stat_bindot() 实现.

有什么建议?

最佳答案

没有一个内置位置完全做到这一点,而且 geom_dotplot也不完全正确,因为它仅适用于一维。我拼凑了一个新职位,该职位可以做正确的事情,但需要手动调整才能使一切正常。

library("proto")
PositionNudge <- proto(ggplot2:::Position, {
objname <- "nudge"
adjust <- function(., data) {
trans_x <- function(x) {
lx <- length(x)
if (lx > 1) {
x + .$width*(seq_len(lx) - ((lx+1)/2))
} else {
x
}
}
trans_y <- function(y) {
ly <- length(y)
if (ly > 1) {
y + .$height*(seq_len(ly) - ((ly+1)/2))
} else {
y
}
}
ddply(data, .(group), transform_position, trans_x=trans_x, trans_y=trans_y)
}
})
position_nudge <- function(width = 0, height = 0) {
PositionNudge$new(width = width, height = height)
}

我称之为轻推,因为我认为的其他事情已经被采取(堆栈,闪避)

使用它
ggplot(example, aes(x, y)) +
geom_point(aes(group=interaction(x,y)), size=5,
position=position_nudge(height=0.03))

enter image description here

您也可以在水平方向轻推
ggplot(example, aes(x, y)) +
geom_point(aes(group=interaction(x,y)), size=5,
position=position_nudge(width=0.03))

enter image description here

您必须将组交互指定为 geom_point 的美学。并且需要将确切的宽度/高度传递给 position_nudge取决于点的大小和输出的大小。例如,对于 4x6 输出,您需要
ggplot(example, aes(x, y)) +
geom_point(aes(group=interaction(x,y)), size=10,
position=position_nudge(height=0.13))

enter image description here

0.13 的值只是反复试验,直到看起来正确为止。从 geom_dotplot学到的一些代码和东西可能可以在这里重新使用以使其更加健壮。此外,除了 example 之外,我还没有使用任何数据对此进行测试。给定,所以它可能会以一些有趣的方式打破它。但如果不出意外,这只是一个开始。

关于r - 堆栈点一个在另一个之上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18774658/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com