簡體   English   中英

如何在R中的ggplot2中閃避點

[英]How to dodge points in ggplot2 in R

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分組以便完全躲避,這可能不是正確的選擇...)

我認為這可能是您想要的,盡管現在您已經解決了。 希望它可以幫助其他人遇到同樣的問題。

一種簡單的方法是像這樣使用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')

看起來像這樣:

geom_dotplot示例

請注意,x(在這種情況下為block)必須是使其起作用的一個因素。

如果不必將它們完美地水平對齊,這是使用geom_jitter的一種快速方法。 您無需按主題分組。

方法1 [簡單]:使用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來計算重復條目的數量。 然后在新的數據框中,對於每個重復的值,將其水平向左移動ε距離。

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)

產生:

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM