簡體   English   中英

geom_jitter 刪除不同數量的點,因為每次運行時都缺少繪圖值

[英]geom_jitter removes different number of points due to missing values for plot each time its run

每次我繪制數據時,R ggplot 中的 geom_jitter 似乎都會刪除不同數量的點。 我懷疑這是由於過度繪制(堆積點)? 例如,如果我創建數據框一次,然后多次運行 ggplot 命令,由於丟失數據(范圍從 0 到 1+),我將刪除不同數量的點。 有沒有辦法確保丟失點的數量一致(或沒有)? 我嘗試修改大小和抖動寬度/高度,但無濟於事。 謝謝!

d <- data.frame(a = rnorm(n = 100, mean = 0, sd = 1), b = rnorm(n = 100, mean = 0, sd = 1))


ggplot(d, aes(a,b)) + geom_point(position=position_jitter(width=0.3, height=.3), size=2) + theme(panel.background=element_blank()) + scale_x_continuous(limits=c(-3, 3)) + scale_y_continuous(limits=c(-3, 3))

抖動將點推到您指定的范圍之外,並且每次運行都會計算噪聲。 試着讓自己抖動一下,這樣它就不會每次都改變,或者移除范圍限制。

set.seed(0)
d <- data.frame(a = rep(-2:2, each=20), b=rnorm(100))

## Specify your own jitter: 0.1 in width, 1 in height in this example
d <- d + rnorm(nrow(d)*2, 0, sd=rep(c(0.1, 1), each=nrow(d)))

## Always 4 rows removed, unless you rejitter
ggplot(d, aes(a, b)) +
  geom_point(size=2) +
  theme(panel.background=element_blank()) +
  scale_x_continuous(limits=c(-3,3)) +
  scale_y_continuous(limits=c(-3,3))

在此處輸入圖片說明

編輯

實際上要簡單得多,只需在運行您擁有的set.seed之前set.seed :)

set.seed(0)
ggplot(d, aes(a,b)) +
  geom_point(position=position_jitter(width=0.3, height=.3), size=2) +
  theme(panel.background=element_blank()) + scale_x_continuous(limits=c(-3, 3)) +
  scale_y_continuous(limits=c(-3, 3))

另一種選擇是不使用scale_x_continuouslimits參數。 相反,使用xlimylim的參數coord_cartesian 這是用於放大繪圖的一部分的代碼。 x 和 y 軸刻度中的限制參數實際上是要繪制的數據的子集。 通常,這沒什么區別,除非您談論的統計摘要包括圖表上不可見的數據。

注意:當您的數據點超出圖表時,您將不會收到警告。

d <- data.frame(a = rnorm(n = 100, mean = 0, sd = 1), 
                b = rnorm(n = 100, mean = 0, sd = 1))


ggplot(d, aes(a,b)) + 
  geom_point(position=position_jitter(width=0.3, height=.3), size=2) + 
  theme(panel.background=element_blank()) + 
  coord_cartesian(xlim=c(-3,3), ylim=c(-3,3))

另一個鮮為人知的選項是通過設置 out of bounds (oob) 參數來更改 scales 處理其邊界的方式。

這真的不是我的想法,而是在這個非常相似的線程中受到用戶 axeman 的很大啟發。

library(ggplot2)
set.seed(0)
d <- data.frame(a = rnorm(n = 100, mean = 0, sd = 1), b = rnorm(n = 100, mean = 0, sd = 1))

ggplot(d, aes(a,b)) + 
  geom_point(position=position_jitter(width=0.3, height=.3), size=2) + 
  theme(panel.background=element_blank()) + 
  scale_x_continuous(limits=c(-3, 3), oob = scales::squish) + 
  scale_y_continuous(limits=c(-3, 3), oob = scales::squish)

reprex 包( v2.0.0 ) 於 2021 年 4 月 27 日創建

暫無
暫無

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

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