ggplot2繪圖系統——幾何對象之線圖
- 曲線:點連線、路徑曲線、時間序列曲線、模型擬合曲線......
- 直線:水平直線、垂直直線、斜線。
1.曲線
對象及其參數。
#路徑圖
geom_path(mapping = ,
data = ,
stat = 'identity',
position = 'identity',
lineend = 'butt', #線段兩端樣式,round/square
linejoin = 'round', #線段交叉樣式,mitre/bevel
linemitre = 1,
arrow = ,
na.rm = FALSE,
show.legend = NA,
inherit.aes = TRUE)
geom_line(mapping = ,
data = ,
stat = 'identity',
position = 'identity',
na.rm = F,
show.legend = NA,
inherit.aes = T)
示例時間序列曲線。
ggplot(economics,aes(date,unemploy))+
geom_line(color='red')
點連線
需要依靠圖層疊加。先畫點和先畫線有細微的區別,即重疊的部分后一個會覆蓋前一個。
df <- data.frame(x=c(1:10),y=sample(10:30,10))
ggplot(df,aes(x,y,))+geom_point(color='blue')+geom_line(color='red')
ggplot(df,aes(x,y,))+geom_line(color='red')+geom_point(color='blue')
線條顏色
dff <- data.frame(x=c(1:10),y=c(1:10))
#連續型線條顏色映射,意義不大
ggplot(dff,aes(x,y,color=x))+
geom_line(linetype=1)+
geom_point(color='blue')
#離散型線條顏色映射
ggplot(economics_long,aes(date,value01))+
geom_line(aes(linetype=variable,color=variable))
2.平滑曲線
參數:
geom_smooth(mapping = ,
data = ,
stat = 'smooth',
position = 'identity',
method = 'auto', #曲線生成方法
formula = y~x,
se=TRUE, #是否顯示95%可信區間
na.rm = F,
span=, #曲線平滑程度0-1,越小越平滑
show.legend = NA,
inherit.aes = T
)
method備選: lm/glm/gam/loess/rlm
。一般樣本量少於1000時,默認loess(樣條回歸);樣本量大於1000時,默認gam(廣義加性模型)。
formula備選:y~log(x)
,或多項式回歸y~ploy(x,2)
a=ggplot(mpg,aes(displ,hwy))+
geom_point()+geom_smooth(span=0.2)
b=ggplot(mpg,aes(displ,hwy))+
geom_point()+geom_smooth(span=0.8)
c=ggplot(mpg,aes(displ,hwy))+
geom_point()+geom_smooth(method='lm',color='red')#線性回歸
library(gridExtra) #圖形組合
gridExtra::grid.arrange(a,b,c,ncol=3)
置信區間
有專門的幾何對象geom_ribbon,即色帶圖。
mydata <- data.frame(time=seq(2000,2016,1),
m_value=rnorm(17,20,5),
sd_value=runif(17,1,3))
ggplot(mydata,aes(time,m_value))+
#均值曲線
geom_line(color='deeppink4',size=1)+
#95%置信區間上限
geom_line(aes(time,m_value+1.96*sd_value),color='black',linetype=2)+
#95%置信區間下限
geom_line(aes(time,m_value-1.96*sd_value),color='black',linetype=2)+
#在兩條置信曲線間添加陰影。
geom_ribbon(aes(time,ymin=m_value-1.96*sd_value,ymax=m_value+1.96*sd_value),
fill='light green',alpha=0.3)
3.直線繪制
函數及其主要參數。
#斜線
geom_abline(...,slope, intercept...) #斜率,截距
#水平直線
geom_hline(..., yintercept...)
#垂直直線
geom_vline(..., xintercept...)
示例。
ggplot(mpg,aes(displ,hwy))+geom_point()+
geom_hline(yintercept = c(15,25,35),linetype=2,color='red')+
geom_vline(xintercept = c(3,4.5,6),linetype=2,color='red')+
geom_abline(slope = 6,intercept = 5,color='blue')