火狐截图_2020-02-11T08-36-22.554Z.png
Add straight lines to a plot: horizontal, vertical and regression lines
ggplot2:添加直线(水平,垂直)和回归线
本教程介绍如何向使用R软件和ggplot2软件包生成的图形添加一条或多条直线。
根据代码运行如下:
1. 水平和垂直线
rm(list = ls())
library(ggplot2)
# Simple scatter plot
sp <- ggplot(data=mtcars, aes(x=wt, y=mpg)) + geom_point()
# Add horizontal line at y = 2O
sp + geom_hline(yintercept=20)
# Change line type and color
sp + geom_hline(yintercept=20, linetype="dashed", color = "red")
# Change line size
sp + geom_hline(yintercept=20, linetype="dashed",
color = "red", size=2)
# geom_vline : Add vertical lines
# Add a vertical line at x = 3
sp + geom_vline(xintercept = 3)
# Change line type, color and size
sp + geom_vline(xintercept = 3, linetype="dotted",
color = "blue", size=1.5)
2. 添加回归线
# Fit regression line
require(stats)
reg<-lm(mpg ~ wt, data = mtcars)
reg
coeff <- coefficients(reg)
# Equation of the line :
eq <- paste0("y = ", round(coeff[2],1), "*x + ", round(coeff[1],1))
# Plot
sp + geom_abline(intercept = 37, slope = -5)+
ggtitle(eq)
# Change line type, color and size
sp + geom_abline(intercept = 37, slope = -5, color="red",
linetype="dashed", size=1.5)+
ggtitle(eq)
sp + stat_smooth(method="lm", se=FALSE)
# geom_segment : Add a line segment
# Add a vertical line segment
sp + geom_segment(aes(x = 4, y = 15, xend = 4, yend = 27))
# Add horizontal line segment
sp + geom_segment(aes(x = 2, y = 15, xend = 3, yend = 15))
library(grid)
sp + geom_segment(aes(x = 5, y = 30, xend = 3.5, yend = 25),
arrow = arrow(length = unit(0.5, "cm")))