gpt4 book ai didi

r - 仅在 ggplot2 重叠时闪避或抖动

转载 作者:行者123 更新时间:2023-12-04 11:12:04 24 4
gpt4 key购买 nike

我想在 ggplot2 中绘制一个图,其值与中心对齐但在重叠处躲避,就像这个(在graphpad棱镜中完成的)

plot in graphpad prism
.

我可以在 ggplot2 中用抖动做的事情看起来像这样

df<-data.frame(response=c(-0.3502294,0.4207441,0.1001638,-0.2401336,-0.2604142,0.4574286,
0.755964,0.9241669,0.8212376,2.037581,0.6440635,0.2714898,1.433149,0.4627742,
0.5639637,0.1610219,0.1516505,-1.322015,-0.2134711,0.8554756,0.400872,1.344739,
0.3743637,0.6329151,0.1467015,0.6313575,0.3989693,0.1940468,-0.06594919,-0.1951204),
group=c(rep("A",10),rep("B",10),rep("C",10)))

set.seed(1234)
ggplot(df,aes(group,response,fill=group))+
geom_point(size=5,pch=21,position=position_jitter(w=.2))+
scale_y_continuous(limits=c(-2,3))

plot in R with ggplot2
.

如何使点与中心对齐并仅在 ggplot2 中的重叠处躲避?

最佳答案

我对您的问题的解决方案是:

  • 将数据划分为重叠点和非重叠点。这可以通过计算先前点之间的差异来完成。如果它小于某个阈值,则该点与某个点重叠,因此在绘制该点时应该应用一些 zitter。否则,该点将被绘制成这样。
  • 使用 geom_point 分别绘制两个数据。

  • 下面是代码,使用上述逻辑。
    library(data.table)

    threshold <- 0.1

    df<-data.frame(response=c(-0.3502294,0.4207441,0.1001638,-0.2401336,-0.2604142,0.4574286,
    0.755964,0.9241669,0.8212376,2.037581,0.6440635,0.2714898,1.433149,0.4627742,
    0.5639637,0.1610219,0.1516505,-1.322015,-0.2134711,0.8554756,0.400872,1.344739,
    0.3743637,0.6329151,0.1467015,0.6313575,0.3989693,0.1940468,-0.06594919,-0.1951204),
    group=c(rep("A",10),rep("B",10),rep("C",10)))

    df1 <- data.table(df[order(df$group, df$response),])
    df1[, diffFromLast:=response - shift(response, n=1, type="lag"), by=group]
    nonZitterPoints <- df1[ is.na(diffFromLast) | (diffFromLast > threshold),]
    zitterPoints <- df1[ which(diffFromLast < threshold),]

    g1 <- ggplot()+
    geom_point(data=nonZitterPoints,aes(group,response,fill=group), size=5,pch=21)+
    scale_y_continuous(limits=c(-2,3))
    g1

    g2 <- g1 + geom_point(data=zitterPoints,aes(group,response,fill=group), size=5,pch=21, position=position_jitter(w=.2))

    g2

    关于r - 仅在 ggplot2 重叠时闪避或抖动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36007598/

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