ggplot2繪圖系統——位置調整函數
可以參數position
來調整,也有專門的函數position_*
系列來設置。
位置函數匯總:
1.排列
並排排列
mean <- runif(12,1,3)
lower <- mean-runif(12,0,2)
upper <- mean+runif(12,0,2)
mydata <- data.frame(group=rep(LETTERS[1:4],each=3),
levels=rep(c('low','middle','high'),4),
mean=mean,lower=lower,upper=upper)
dodge <- position_dodge(width = 0.5)
ggplot(mydata,aes(levels,ymin=lower,ymax=upper,color=as.factor(group)))+
geom_errorbar(position = dodge,width=0.2,size=1.2)+
geom_point(aes(levels,mean),position = dodge,size=4)
堆棧排列
death <- c('胃癌','肺癌','食管癌','肝癌','腦癌')
percent <- c(0.21,0.28,0.09,0.32,0.1)
pro=scales::percent(percent)
cancer <- data.frame(death=death,per=percent,
disease='cancer',prop=pro)
ggplot(cancer,aes(x=disease,y=per,fill=death))+
geom_bar(stat = 'identity')+
geom_text(aes(label=prop),
position = position_stack(vjust = 0.5),size=6.5)
2.擾動點
a <- ggplot(mpg,aes(class,hwy))+geom_boxplot()+geom_point()
b <- ggplot(mpg,aes(class,hwy))+geom_boxplot()+
geom_jitter()
c <- ggplot(mpg,aes(class,hwy))+geom_boxplot()+
geom_point(position = 'jitter')
grid.arrange(a,b,c,ncol=3)
上圖b和c的擾動方式稍有不同。
3.水平和垂直的調整
包括hjust/vjust
,position_nudge
等,注意nudge(推動)不能作為postion參數的選項,即不能類似geom_point(position='nudge')
df <- data.frame(x=c(1,3,2,5),y=c('a','b','c','d'))
#在點的原位置添加標簽
a <- ggplot(df,aes(x,y))+geom_point()+geom_text(aes(label=y))
#標簽向下移動一個單位
b <- ggplot(df,aes(x,y))+geom_point()+geom_text(aes(label=y),
position=position_nudge(y=-0.1))
grid.arrange(a,b,ncol=2)
4.有規則擾動
同樣只能作為函數position_jitterdodge
使用。
同一組內,紅色點只出現在紅色盒形上,不會出現在其他位置。
dsub <- diamonds[sample(nrow(diamonds),1000),]
#無規則
a <- ggplot(dsub,aes(x=cut,y=carat,fill=clarity))+
geom_boxplot(outlier.size = 0)+
geom_point(pch=21,position = position_jitter())
#有規則
b <- ggplot(dsub,aes(x=cut,y=carat,fill=clarity))+
geom_boxplot(outlier.size = 0)+
geom_point(pch=21,position = position_jitterdodge())
grid.arrange(a,b,ncol=2)