【问题标题】:How to dodge points in ggplot2 in R如何在R中的ggplot2中躲避点
【发布时间】:2013-11-26 04:05:29
【问题描述】:
df = data.frame(subj=c(1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10), block=factor(rep(c(1,2),10)), acc=c(0.75,0.83,0.58,0.75,0.58,0.83,0.92,0.83,0.83,0.67,0.75,0.5,0.67,0.83,0.92,0.58,0.75,0.5,0.67,0.67))
ggplot(df,aes(block,acc,group=subj)) + geom_point(position=position_dodge(width=0.3)) + ylim(0,1) + labs(x='Block',y='Accuracy')

如何让点在水平方向上均匀地相互闪避? (我按 subj 分组是为了让它完全躲避,这可能不是正确的做法......)

【问题讨论】:

    标签: r ggplot2 position


    【解决方案1】:

    我认为这可能是您正在寻找的东西,尽管毫无疑问您现在已经解决了它。 希望它能帮助遇到同样问题的其他人。

    一个简单的方法是像这样使用geom_dotplot

    ggplot(df,aes(x=block,y=acc)) + 
    geom_dotplot(binaxis = "y", stackdir = "center", binwidth = 0.03)  + ylim(0,1) + labs(x='Block',y='Accuracy')
    

    看起来像这样:

    请注意,x(在这种情况下为块)必须是它起作用的一个因素。

    【讨论】:

      【解决方案2】:

      如果它们不必完全水平对齐,这是一种快速的方法,使用geom_jitter。您不需要按主题分组。

      方法一【更简单】:使用geom_jitter()

      ggplot(df,aes(x=block,y=acc)) + geom_jitter(position=position_jitter(0.05)) + ylim(0,1) + labs(x='Block',y='Accuracy')
      

      调整抖动宽度以获得更大程度的抖动。

      产生:

      方法2:确定性地计算每一行的抖动值

      我们首先使用aggregate 来计算重复条目的数量。然后在一个新的数据框中,对于每个重复的值,将其水平向左移动一个 epsilon 距离。

      df$subj <- NULL #drop this so that aggregate works.
      
      #a new data frame that shows duplicated values
      agg.df <- aggregate(list(numdup=seq_len(nrow(df))), df, length)
      agg.df$block <- as.numeric(agg.df$block) #block is not a factor
      #      block  acc numdup
      #1     2      0.50      2
      #2     1      0.58      2
      #3     2      0.58      1
      #4     1      0.67      2
      #...    
      epsilon <- 0.02 #jitter distance
      
      new.df <- NULL #create an expanded dataframe, with block value jittered deterministically
      r <- 0
      for (i in 1:nrow(agg.df)) {
        for (j in 1:agg.df$numdup[i]) {
          r <- r+1 #row counter in the expanded df
          new.df$block[r] <- agg.df$block[i]
          new.df$acc[r] <- agg.df$acc[i]
          new.df$jit.value[r] <- agg.df$block[i] - (j-1)*epsilon    
        }
      }
      new.df <- as.data.frame(new.df)
      ggplot(new.df,aes(x=jit.value,y=acc)) + geom_point(size=2) + ylim(0,1)  + labs(x='Block',y='Accuracy') + xlim(0,3)
      

      产生:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-13
        • 2023-03-31
        • 1970-01-01
        • 2013-11-15
        • 2014-11-05
        • 1970-01-01
        相关资源
        最近更新 更多