2015-02-23 46 views
1

我正在繪製行數據,併爲統計計算的擬合值添加了一段可信區間和一個黑點。ggplot指定分類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)) 

和括號的所有可能的組合。

當然我在網上查找類似的圖表,但找不到任何 - >通常垂直線是直接從數據點計算出來的,而不是添加到不同列的行數據中!

+1

請提供[**最小的,自包含的例子**](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-重複性示例/ 5963610#5963610) – Henrik 2015-02-23 11:33:54

回答

1

如果你的x值真的是因素,那麼你可以使用as.numeric()geom_segment()的x值和最後geom_point()能夠添加一些小的常數,然後移動線和點。

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") 

enter image description here

+0

好的,謝謝,我曾嘗試過,但只與'數字'而不是'as.numeric',我得到以下錯誤:'數值錯誤(pb_cluster):無效'長度'參數' – 2015-02-23 13:32:29