Fail to add a linear trend line on a barplot in R

4.2k views Asked by At

I have created a barplot using barplot and then I want to show the linear trend. I use abline but the linear trend line does not show in the figure. I wonder what the problem is. Thanks.

set.seed(100)
Mydata=rnorm(65)
Year=1950:2014
barplot(Mydata)
fit=lm(Mydata~Year)
abline(fit)

enter image description here

As @G5W points out, fit=lm(Mydata~I(Year-1950)). But the new problem is that the trend line is too "long". As shown in the second figure, the trend line goes beyond the barplot. Is there any advice?

enter image description here

2

There are 2 answers

3
Icaro Bombonato On BEST ANSWER

If you can use ggplot:

library(ggplot2)    

df <- data.frame(Mydata, Year)

ggplot(df, aes(x = Year, y = Mydata)) + 
  geom_bar(stat = "identity") + 
  geom_smooth(method = "lm")

enter image description here

2
d.b On

To expand on @bouncyball's comment, use a higher value of line width (lwd) to resemble barplot if you want.

plot(Year, Mydata, type = 'h',lwd=5,col = "grey")
abline(fit, lty =2)

EDIT

First copy this function

barplot2 <- function(x, y, lty = 1, lwd = 1, col = "grey", border = "black"){
w = ((max(x) - min(x))/length(x)) * 0.75
plot(x, y, type = 'p', pch = NA, yaxt = "n", xaxt = "n", xlab = "", ylab = "")
for (i in 1:length(x)){
x1  = x[i] - w/2
x2 = x[i] + w/2
y1 = 0
y2 = y[i]
polygon(x = c(x1,x2,x2,x1), y = c(y1,y1,y2,y2), lty = lty, lwd = lwd, col = col, border = border)
}
}

Then make the barplot

barplot2(Year,Mydata)

Then add the ablineclip from plotrix library

ablineclip(fit, x1 = min(Year), x2 = max(Year), y1 = min(Mydata), y2 = max(Mydata))

enter image description here