R語言ggplot2包之畫散點圖

引言

散點圖是描繪兩個連續型變量之間關係的圖形,特別是在觀察兩個變量之間的相關關係時特別好使。

散點圖基本操作

aes中的x,y值分別表示在x,y軸的變量;geom_point表示增加三點圖圖層,其中的size控制點的大小,shape控制形狀,一共25個,爲0-25。

library(gcookbook)
library(ggplot2)
head(heightweight)
#  sex ageYear ageMonth heightIn weightLb
#1   f   11.92      143     56.3     85.0
#2   f   12.92      155     62.3    105.0
#3   f   12.75      153     63.3    108.0
#4   f   13.42      161     59.0     92.0
#5   f   15.92      191     62.5    112.5
#6   f   14.25      171     62.5    112.0
ggplot(heightweight, aes(x=ageYear, y=heightIn)) + geom_point(size=3,shape=21)

這裏寫圖片描述

分組散點圖

散點圖分組有兩種方式,一種利用shape,以點的形狀來區分各種;一種用color,以點的顏色來區分.但是得記住,分組的變量必須爲因子變量或者字符串。

ggplot(heightweight, aes(x=ageYear, y=heightIn, colour=sex)) + geom_point()#以顏色區分
ggplot(heightweight, aes(x=ageYear, y=heightIn, shape=sex)) + geom_point()#以形狀區分

這裏寫圖片描述
這裏寫圖片描述

解決點覆蓋問題

當點的密度大時,我們可以改變點的透明度來區分各個點。當然我們可以使用bin的方法來區分,這種方法是把點的形狀設定爲長方形,密度越大的長方形區域越透明。

ggplot(diamonds, aes(x=carat, y=price))+ geom_point(alpha=.1)
ggplot(diamonds, aes(x=carat, y=price))+ geom_point(alpha=.01)
ggplot(diamonds, aes(x=carat, y=price))+ stat_bin2d()

這裏寫圖片描述
這裏寫圖片描述
這裏寫圖片描述

當其中的一個或者兩個變量爲離散型數據時,也會導致覆蓋的問題。我們可以使用jitter方法和box的方法。

ggplot(ChickWeight, aes(x=Time, y=weight))+geom_point()
ggplot(ChickWeight, aes(x=Time, y=weight))+geom_point(position="jitter")
#position="jitter"等價於geom_jitter,即下面的方法
ggplot(ChickWeight, aes(x=Time, y=weight))+geom_point(position=position_jitter(width=.5, height=0))
ggplot(ChickWeight, aes(x=Time, y=weight))+ geom_boxplot(aes(group=Time))

這裏寫圖片描述
這裏寫圖片描述
這裏寫圖片描述

增加擬合的迴歸線

爲了更好的看出兩個變量之間的關係,我們還可以擬合迴歸線,用stat_smooth(method=lm)函數即可。

ggplot(heightweight, aes(x=ageYear, y=heightIn))+geom_point() + stat_smooth(method=lm)
#該回歸直線的置信區間默認的置信度是95%,我們也可以對其進行修改。
ggplot(heightweight, aes(x=ageYear, y=heightIn))+ geom_point() + stat_smooth(method=lm, level=0.99)#99%的置信度
#也可以不顯示置信區間
ggplot(heightweight, aes(x=ageYear, y=heightIn))+ geom_point(colour="grey60") + stat_smooth(method=lm, se=FALSE)

這裏寫圖片描述
這裏寫圖片描述
這裏寫圖片描述
還有很多關於增迴歸線的技術,這裏暫時不涉及,這本身還需要相關的計量知識來支撐的,需要了解的大家再查看書籍對應部分即可。

給點增加標籤

有時候,當點數量不多時,我們想讓點顯示名稱來進行區分,用geom_text就能做到,只要給參數label賦予對應的名字即可。

ggplot(subset(countries, Year==2009 & healthexp>2000),
aes(x=healthexp, y=infmortality)) +geom_text(aes(label=Name), size=4)

這裏寫圖片描述

氣泡圖

有時候我們想展示三個變量之間的關係,這時氣泡圖是一個很好的工具。

cdat <- subset(countries, Year==2009 &
Name %in% c("Canada", "Ireland", "United Kingdom", "United States",
"New Zealand", "Iceland", "Japan", "Luxembourg",
"Netherlands", "Switzerland"))
#氣泡大小用size參數進行控制,把第三個變量賦值給該參數就行。
ggplot(cdat, aes(x=healthexp, y=infmortality, size=GDP)) +
geom_point(shape=21, colour="black", fill="cornsilk")

這裏寫圖片描述

創建散點矩陣圖

散點矩陣圖是展示多個變量相互之間的一個極好展示。

c2009 <- subset(countries, Year==2009,
select=c(Name, GDP, laborrate, healthexp, infmortality))
pairs(c2009[,2:5])

這裏寫圖片描述
這裏我們不用ggplot2包進行,這是因爲該包不太適合對這類圖形進行展示。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章