1
votes

I have some data about the percentages of temperature for different time periods and I want to create a barplot showing those percentages and then add a linear regression line showing the trend. Although i manage to get the first graph, I fail to add a straight linear regression line

Basically I try to make a barplot with these tx_1 data

tx_1<-c(0.055,0.051,0.057,0.049,0.061,0.045)

The plot without the line

The plot with the non-straight line

mypath<-file.path("C:\\tx5\\1.jpeg")
jpeg(file = mypath,width = 1200, height = 600)
plot.dim<-barplot(get(name),
                  space= 2,
                  ylim=c(0,0.15),
                  main = "Percentage of days when Tmax < 5th percentile",
                  xlab = "Time Periods",
                  ylab = "Percentage",
                  names.arg = c("1975-1984", "1985-1990", "1991-1996", "1997-2002", "2003-2008", "2009-2014"),
                  col = "darkred",
                  horiz = FALSE)
dev.off()

I tried using ggplot also, but with no luck

1
You can achieve that by first computing the linear model with the lm function and then adding the line with the abline function (see here for an example). I'm really not sure about the validity of such a model, though...Vincent Guillemot

1 Answers

1
votes

Here i have included both a line connecting each observation and a overall best linear fit line. Hope this helps.

library(tidyverse)

year <- tribble(~ Year,~ Percent,
        94,0.055,
        95,0.051,
        96,0.057,
        97,0.049,
        98,0.061,
        99,0.045)

ggplot(year,aes(Year,Percent)) + 
  geom_bar(stat = "identity") + 
  geom_line() + 
  geom_smooth(method = "lm",se = F)