Fail to add linear regression line in barplot

雨燕双飞 提交于 2021-01-28 18:30:38

问题


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)

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:


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)


来源:https://stackoverflow.com/questions/58911673/fail-to-add-linear-regression-line-in-barplot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!