2017-08-05 83 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

相关问题