我使用#[link_args...]
创建了一个条形图,然后我想显示线性趋势。我使用barplot
但线性趋势线未在图中显示。我想知道问题是什么。感谢。
abline
正如@ G5W指出的那样,set.seed(100)
Mydata=rnorm(65)
Year=1950:2014
barplot(Mydata)
fit=lm(Mydata~Year)
abline(fit)
。但新问题是趋势线太长了#34;如第二张图所示,趋势线超出了条形图。有什么建议吗?
答案 0 :(得分:3)
如果你可以使用ggplot:
library(ggplot2)
df <- data.frame(Mydata, Year)
ggplot(df, aes(x = Year, y = Mydata)) +
geom_bar(stat = "identity") +
geom_smooth(method = "lm")
答案 1 :(得分:1)
要扩展@ bouncyball的评论,请根据需要使用较高的线宽值(lwd
)来代替barplot
。
plot(Year, Mydata, type = 'h',lwd=5,col = "grey")
abline(fit, lty =2)
修改强>
首先复制此功能
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)
}
}
然后制作条形图
barplot2(Year,Mydata)
然后从ablineclip
库
plotrix
ablineclip(fit, x1 = min(Year), x2 = max(Year), y1 = min(Mydata), y2 = max(Mydata))