2017-08-05 40 views
0

我想製作一個圖表來繪製兩組的方塊圖,併爲每個組添加回歸線。我看到了一些可用的例子,但沒有一個能夠實現我的目標。兩組的方塊圖將回歸線添加到每個組

我的數據幀是像這樣:

df<- data.frame(cont.burnint= c(rep(2,10), rep(12, 10), rep(25, 10)), 
        variable= rep(c("divA","divC"), 30), 
        value= sample(x = seq(-1,4,0.5), size = 60, replace = 
        TRUE)) 

我想產生這樣一個圖:enter image description here

不過,我想點更改爲箱形圖的每個組。我還沒有發現有用的例子如下所示:

Add geom_smooth to boxplot Adding a simple lm trend line to a ggplot boxplot

代碼我已發現可用迄今,改變我的連續可變cont.burnint到的因子和重新排序從c x值(2,12 ,25)至c(12,2,25)。此外,ggplot示例中的迴歸線(請參閱鏈接)不會擴展到y軸。我希望迴歸線延伸到y軸。第三,箱型圖相互偏離,我希望有一個選項可以使兩個組的箱形圖保持相同的x值。

所以基本上,我想改變提供給盒子和晶須圖的圖中的點,並保持所有其他部分相同,如上例所示。我不介意在劇情下添加一個圖例,並且使文本和線條更加大膽。

下面是上面的示例代碼:

plot(as.numeric(as.character(manovadata$cont.burnint)),manovadata$divA,type="p",col="black", xlab="Burn Interval (yr)", ylab="Interaction Diveristy", bty="n", cex.lab=1.5) 

points(as.numeric(as.character(manovadata$cont.burnint)),manovadata$divC,col="grey") 

abline(lm(manovadata$divA~as.numeric(as.character(manovadata$cont.burnint)), manovadata),col="black",lty=1) 

abline(lm(manovadata$divC~as.numeric(as.character(manovadata$cont.burnint)), manovadata),col="grey",lty=1) 

回答

0

我無法想象爲什麼你想覆蓋箱線圖,但在這裏,你走我想:

library(ggplot2) 

df$cont.burnint <- as.factor(df$cont.burnint) 

ggplot(df, aes(x=cont.burnint, y=value, col=variable))+ 
    geom_boxplot(position=position_dodge(width=0), alpha=0.5)+ 
    geom_smooth(aes(group=variable), method="lm") 

我添加了一些透明度使用alpha的箱形圖使它們在彼此頂部可見。

更新:

ggplot(df, aes(x=cont.burnint, y=value, col=variable))+ 
    geom_boxplot(aes(group=paste(variable,cont.burnint)))+ 
    geom_smooth(aes(group=variable), method="lm", fullrange=T, se=F)+xlim(0,30) 
+0

謝謝您的幫助...但是你的解決方案不會延長迴歸線與y軸。另外,通過將cont.burnint更改爲一個因子,可以對軸進行重新排序。我想命令出現c(2,12,25)而不是c(12,2,25)。你是對的,但是,我不喜歡箱子堆積,所以它們是交錯的,會更好 – Danielle

+0

我更新了我的答案:) – user3640617

相關問題