[英]Adding point in geom_linerange() and reduce the gap in R ggplot2
[英]Issue using position dodge vertically in ggplots with geom_linerange in R
我對 R 比較陌生,我在使用 geom_linerange 和 position_dodge 與 ggplot 避免重疊線范圍時遇到問題。 我正在比較研究數據中每個人的 2 組不同的年齡范圍。 我想並排顯示兩個范圍,而不是顯示在同一 ID 行上。 這是數據:
> dput(data)
structure(list(ID = c("A", "B", "C", "D", "E", "F", "G", "H",
"I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U",
"V", "W", "X", "Y", "Z"), Age_Range1_Start = c(39L, 21L, 28L,
35L, 35L, 20L, 21L, 28L, 20L, 29L, 28L, 20L, 49L, 20L, 39L, 21L,
39L, 21L, 20L, 28L, 30L, 29L, 21L, 28L, 29L, 35L), Age_Range1_End = c(69L,
42L, 52L, 57L, 57L, 43L, 42L, 52L, 43L, 44L, 52L, 43L, 65L, 43L,
69L, 42L, 69L, 42L, 43L, 52L, 54L, 44L, 42L, 52L, 44L, 57L),
Age_Range2_Start = c(46L, 43L, 49L, 46L, 48L, 34L, 37L, 45L,
44L, 46L, 37L, 43L, 51L, 45L, 48L, 36L, 53L, 44L, 24L, 43L,
45L, 49L, 34L, 45L, 22L, 30L), Age_Range2_End = c(87L, 80L,
92L, 86L, 90L, 64L, 69L, 83L, 81L, 85L, 68L, 80L, 97L, 84L,
89L, 68L, 100L, 83L, 45L, 82L, 83L, 92L, 64L, 84L, 42L, 56L
)), class = "data.frame", row.names = c(NA, -26L))
>
這是我使用的 R 代碼
ggplot(data) + theme_minimal() + coord_flip() +
geom_linerange(aes(x=ID, ymin=Age_Range1_Start, ymax=Age_Range1_End, color="Method 1", size=1.5)) +
geom_linerange(aes(x=ID, ymin=Age_Range2_Start, ymax=Age_Range2_End, color="Method 2", size=1.5), position=position_dodge(width=1)) +
labs(x="ID", y="Age Range", title="Method Age Range Comparison")
它產生以下情節:
是否可以移動(或躲避)方法 2 的線條范圍,使其看起來略低於或低於方法 1 的年齡范圍? 我不明白為什么 position_dodge 代碼不改變值。
預先感謝您提供任何幫助或建議。
如果您以另一種格式組織數據,則可以執行以下操作:
library(ggplot2)
data = data.frame(
ID = rep(c('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'), 2),
Start = c(39, 21, 28, 35, 35, 20, 21, 28, 46, 43, 49, 46, 48, 34, 37, 45),
End = c(69, 42, 52, 57, 57, 43, 42, 52, 87, 80, 92, 86, 90, 64, 69, 83),
Method = c(rep(1, 8), rep(2, 8))
)
data$Method = as.factor(data$Method)
ggplot(data) +
theme_minimal() +
coord_flip() +
geom_linerange(aes(x = ID, ymin = Start, ymax = End, colour = Method),
size = 1.5, position = position_dodge2(width = 0.5)) +
labs(x = 'ID', y = 'Age Range', title = 'Method Age Range Comparison')
這是輸出:
請注意,我將起點和終點放在一起。 然后,我將它們分別標記為方法 1 或 2。
還記得在翻轉坐標時使用position_dodge2()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.