【问题标题】:Box plot of two groups add regression line to each group两组箱线图为每组添加回归线
【发布时间】:2017-08-05 14:17:31
【问题描述】:

我想制作一个图表,为两组绘制箱形图,并为每组添加一条回归线。我已经看到了一些可用的示例,但没有一个可以实现我的目标。

我的数据框是这样的:

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

我想生成如下图:

但是,我想将每个组的点更改为箱线图。我没有在以下内容中找到有用的示例:

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

到目前为止,我发现可用的代码将我的连续变量 cont.burnint 更改为一个因子,并将 x 值从 c(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)

【问题讨论】:

    标签: r plot


    【解决方案1】:

    我无法想象你为什么要叠加箱线图,但我认为你可以这样做:

    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)
    

    【讨论】:

    • 感谢您的帮助...但是您的解决方案没有将回归线延伸到 y 轴。此外,通过将 cont.burnint 更改为一个因子,它会重新排序轴。我希望订单显示为 c(2,12,25) 而不是 c(12,2,25)。但是你是对的,我不喜欢堆叠的箱形图,所以它们交错排列会更好
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-26
    • 1970-01-01
    • 2021-02-03
    • 1970-01-01
    • 1970-01-01
    • 2021-04-28
    • 2021-09-08
    相关资源
    最近更新 更多