[英]ggplot2 and jitter/dodge points by a group
我有“海拔”作為我的 y 軸,我希望它作為一個離散變量(換句話說,我希望每個海拔之間的空間相等,而不是相對於數值差異)。 我的 x 軸是“時間”(朱利安日期)。
mydata2<- data.frame(
"Elevation" = c(rep(c(1200),10),rep(c(1325.5),10),rep(c(1350.75),10), rep(c(1550.66),10)),
"Sex" = c(rep(c("F","M"),20)),
"Type" = c(rep(c("emerge","emerge","endhet","endhet","immerge","immerge","melt","melt", "storpor","storpor"),4)),
"mean" = c(rep(c(104,100,102,80,185,210,84,84,188,208,104,87,101,82, 183,188,83,83,190,189),2))
"se"=c(rep(c(.1,.01,.2,.02,.03),4)))
mydata2$Sex<-factor(mydata2$Sex))
mydata2$Type<-factor(mydata2$Type))
mydata2$Elevation<-factor(mydata2$Elevation))
at<-ggplot(mydata2, aes(y = mean, x = Elevation,color=Type, group=Sex)) +
geom_pointrange(aes(ymin = mean-se, ymax = mean+se),
position=position_jitter(width=0.2,height=.1),
linetype='solid') +
facet_grid(Sex~season,scales = "free")+
coord_flip()
at
理想情況下,我希望每個“類型”都垂直分開。 當我只抖動或躲避那些緊密分開且不均勻的那些時。 有沒有辦法強制每個“類型”稍微移動,以便它們都在自己的線上? 我試圖通過給每種類型一個略有不同的“高度”來強制它,但最終我得到了一個凌亂的 y 軸(我想不出一種方法來保持這個點,但不顯示具有離散比例的所有刻度線)。
感謝您的幫助。
如果要將數值用作離散值,則應使用as.factor
。 在您的示例中,嘗試使用x = as.factor(Elevation)
。
此外,我會建議使用position = position_dodge()
來從不同條件下獲取對應於相同海拔的點並排繪制
ggplot(mydata2, aes(y = mean, x = as.factor(Elevation),color=Type, group=Sex)) +
geom_pointrange(aes(ymin = mean-se, ymax = mean+se),
position=position_dodge(),
linetype='solid') +
facet_grid(Sex~season,scales = "free")+
coord_flip()
使用 OP 提供的示例數據進行編輯
使用您的數據集,我無法根據您的觀點繪制范圍。 因此,我使用dplyr
包創建了兩個變量Lower
和Upper
。
然后,我沒有通過您在問題中提供的 commdnas facotr(...)
而是使用as.factor(Elevation)
和position_dodge(0.9)
進行繪圖以獲得以下圖:
library(tidyverse)
mydata2 %>% mutate(Lower = mean-se*100, Upper = mean+se*100) %>%
ggplot(., aes( x = as.factor(Elevation), y = mean, color = Type))+
geom_pointrange(aes(ymin = Lower, ymax = Upper), linetype = "solid", position = position_dodge(0.9))+
facet_grid(Sex~., scales = "free")+
coord_flip()
它看起來像您要找的東西嗎?
數據您提供的數據集包含的錯誤很少(括號過多),因此我在這里更正。
mydata2<- data.frame(
"Elevation" = c(rep(c(1200),10),rep(c(1325.5),10),rep(c(1350.75),10), rep(c(1550.66),10)),
"Sex" = rep(c("F","M"),20),
"Type" = rep(c("emerge","emerge","endhet","endhet","immerge","immerge","melt","melt", "storpor","storpor"),4),
"mean" = rep(c(104,100,102,80,185,210,84,84,188,208,104,87,101,82, 183,188,83,83,190,189),2),
"se"=rep(c(.1,.1,.2,.05,.03),4))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.