【ggplot2繪圖二:散點圖】

2021.4.23
持續更新中。。。

參考:《R數據可視化手冊》、學術數據分析及可視化

1. 理解數據與圖層

library(ggplot2)
set.seed(999)
diamonds <- diamonds[sample(1:53940, 5000, replace = F),]
#數據寫在底層,則對后續所有圖層有效
ggplot(diamonds, aes(carat, price, color = cut)) +
  geom_point(shape = 18)
#數據寫在單一圖層在,則只對該圖層有效
ggplot() +
  geom_point(data = diamonds, aes(carat, price, color = cut), shape = 18)

數據在初始圖層ggplot()中定義時,對后續所有圖層有效,當多組數據時,可在每個圖層分別定義數據


2. 簡單散點圖

library(ggplot2)
library(tidyr)

df <- iris
#修改表頭
colnames(df) <- c('SepalL','SepalW','PetalL','PetalW','Species')
#寬數據變長數據
df <- gather(df, Index, Value, -Species)
#將Index和Value變量映射x軸和y軸,同時將Species分類變量映射顏色和形狀
ggplot(df, aes(Index, Value, color = Species, shape = Species))+
  #設置點的大小,透明度,類型
  geom_point(size = 3, alpha = .5, shape = 18)+
  #設置每個點的文本,去重復,文本位置
  geom_text(aes(label = Species), check_overlap = TRUE, vjust=4, hjust=0)
##添加單個標簽文本
##annotate('text', x = 6, y = 7.5, label = 'Scatter plot with a linear fit line',
##         color = 'red', fontface = 'italic')

  1. 映射給顏色或大小的變量是分類變量時,則是對數據進行分組;若映射的是連續性變量,則是一個漸變過程。
  2. scale_shape_manual()scale_color_brewer函數可以后續自定義圖形和顏色。scale_color_brewer()調色盤選擇:https://www.datavis.ca/sasmac/brewerpal.html

3. 散點圖 +擬合線

3.1 線性擬合

ggplot(iris, aes(Sepal.Length, Petal.Length))+
  geom_point()+
  #設置擬合線是否顯示置信域,顏色,大小和類型
  geom_smooth(method = 'lm', formula = y ~ x, se = F, 
              color = 'red', size = 2, linetype = 3)
##若要虛化擬合線,需要換一個函數
##geom_line(stat = 'smooth', method = 'lm', se = F,
##         color = 'red', size = 2, linetype = 6, alpha = .2)
  1. 可選的形狀和線型:
    形狀和線型
  2. color參數設置在aes()之外,則所有的變量都設置成一個顏色,而在aes()之內,會給不同的因子或者數值上色
  3. 模型除了y ~ x之外,也可以用y ~ log(x)y ~ poly(x, 2)y ~ poly(x, 3)等多項式

3.2 添加新構建模型的擬合線

思路:首先創建回歸模型,然后根據模型計算變量和預測值的大小,最后繪制回歸線即可。

library(ggplot2)
library(gcookbook)
rm(list=ls())
#用lm()函數創建回歸模型
model <-  lm(heightIn ~ ageYear + I(ageYear^2), heightweight)
#創建包含變量ageYear最小值和最大值的列
xmin <-  min(heightweight$ageYear)
xmax <-  max(heightweight$ageYear)
predicted <-  data.frame(ageYear=seq(xmin, xmax, length.out=100))
#計算變量heightIn的預測值,之后predicted包含兩個變量ageYear和heightln
predicted$heightIn <-  predict(model, predicted)

#繪制點圖
p <- ggplot(heightweight, aes(x=ageYear, y=heightIn)) +
     geom_point()+
#添加回歸曲線
     geom_line(data=predicted, size=1)

4. 繪制兩組來自不同數據的點圖

library(tidyr)
library(ggplot2)
df <- iris
head(df)
#修改表頭
colnames(df) <- c('SpealL', 'SpepalW', 'PetalL', 'PetalW', 'Species')
#寬數據變長數據
df <- gather(df, Index, Value, -Species)
df

ggplot()+
  geom_point(data = df, aes(Species, Value, color =Index))+
  geom_point(data = iris, aes(Species, Sepal.Width, color = Species))

繪制多組不同數據時ggplot()不接任何參數,后續繪圖函數調用參數data =分別指明具體的數據名。


5. 氣泡圖

ggplot(mtcars, aes(wt, mpg, color = factor(cyl)))+
  #將cyl影射給大小
  geom_point(aes(size = cyl))+
  #添加坐標
  scale_size(breaks = c(4,6,8))
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容