0

I want to make a graph that graphs box plots for two groups and adds a regression line for each group. I have seen a few examples available, but none achieving my goal.

My dataframe is like so:

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

I would like to produce a graph like: enter image description here

However, I want to change the points to a box plot for each group. I have not found helpful examples in the following:

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

The code I have found available thus far, changes my continuous variable cont.burnint to a factor and reorders the x-values from c(2,12,25) to c(12,2,25). Also, the regression lines in the ggplot examples (refer to link)do not extend to the y axis. I would like the regression line to extend to the y-axis. Thirdly, the box plots become off set from each other and I would like an option that keeps the box plot for both groups on the same x value.

So basically, I want to change the points in the graph provided to a box and whisker plot and keep all else the same, in the example above. I wouldn't mind adding a legend below the plot and making text and lines bolder too.

Here is the code for the example above:

 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)
Danielle
  • 785
  • 7
  • 15

1 Answers1

0

I can't imagine why you want overlaying boxplots, but here you go I think:

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

I added some transparency to the boxplots using alpha to make them visible on top of each other.

Update:

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)
user3640617
  • 1,546
  • 13
  • 21
  • Thank you for your help...however your solution does not extend the regression line to the y axis. Also, by changing cont.burnint to a factor it reorders the axis. I want the order to appear c(2,12,25) not c(12,2,25). You are right however, I do not like the box plots stacked so it they are staggered that would be better – Danielle Aug 05 '17 at 16:49