[英]ggplot specify position of vertical segments for categorical x r
我正在繪制行數據,並添加了一段可信區間和一個黑點,用於統計計算的擬合值。
我的問題是,我希望這些行(和黑點)相對於行數據略微(水平)移動。
我嘗試了抖動及其所有可能的組合,結果很糟糕,因為我從不同的列獲取y的開始和結束值...因此,隨着抖動的出現,線條不再水平。
我試圖將固定值添加到x(pb_values),但是由於我的x是一個因數,因此它給了我一個錯誤。
dat_stack1(我的數據集):
dat_stack1<-data.frame(pb_cluster= rep(3:5, 6))
dat_stack1$pb_cluster<-factor(dat_stack1$pb_cluster)
dat_stack1$total<-c(28, 12, 3, 326, 14, 125, 74, 40, 115, 382, 70, 36, 36, 23, 28,185,19,107)
dat_stack1$couple<-factor(c(1, 1, 1, 2, 2, 2, 5, 5, 5, 8, 8, 8, 9, 9, 9, 11, 11, 11))
dat_stack1$lower<-c(55, 0.1851138, 8.9413495, 55.5002200, 0.1851138, 8.9413495, 55.5002200, 0.1851138, 8.9413495, 55.5002200, 0.1851138, 8.9413495, 55.5002200, 0.1851138, 8.9413495, 55.5002200, 0.1851138, 8.9413495)
dat_stack1$upper<-c(225.47047, 68.04097, 114.92182, 225.47047, 68.04097, 114.92182, 225.47047, 68.04097, 114.92182, 225.47047,68.04097,114.92182, 225.47047, 68.04097, 114.92182, 225.47047, 68.04097, 114.92182)
dat_stack1$fit<-c(124.93260, 18.87026, 46.84022,124.93260, 18.87026,46.84022,124.93260, 18.87026, 46.84022, 124.93260, 18.87026, 46.84022,124.93260, 18.87026, 46.84022, 124.93260 ,18.87026 ,46.84022)
g<-g_stack<-ggplot(data=dat_stack1, aes(x=pb_cluster, y = total, shape=couple))+
geom_point()+
scale_x_discrete(limits=c("3","4","5"), labels=c("mate", "familiar","unfamiliar"))+
theme(axis.text.x = element_text(angle=90))+
geom_segment(aes(x=pb_cluster, xend=pb_cluster, y = lower, yend = upper))+
geom_point(aes(x=pb_cluster, y = fit),color="black")
不幸的是,我的聲譽太低,無法發布圖片!但是代碼現在可以重現了
知道如何移動這些垂直線嗎?
我試過的
geom_segment(aes(x=pb_cluster, xend=pb_cluster,
y = lower, yend = upper)+position="jitter")
和
geom_segment(aes(x=pb_cluster +0.1, xend=pb_cluster+0.1,
y = lower, yend = upper))
以及所有可能的括號組合。
當然,我在網上尋找類似的圖形,但找不到任何圖形->通常,垂直線是直接從數據點計算而來,而不是添加到不同列的行數據中!
如果您的x值確實是因子,則可以在geom_segment()
和最后一個geom_point()
x值周圍使用as.numeric()
來添加一些小常數,然后移動線和點。
ggplot(data=dat_stack1, aes(x=pb_cluster, y = total, shape=couple))+
geom_point()+
scale_x_discrete(limits=c("3","4","5"),labels=c("mate", "familiar","unfamiliar"))+
theme(axis.text.x = element_text(angle=90))+
geom_segment(aes(x=as.numeric(pb_cluster)+.1, xend=as.numeric(pb_cluster)+.1,
y = lower, yend = upper))+
geom_point(aes(x=as.numeric(pb_cluster)+0.1, y = fit),color="black")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.