2021.4.23
持續(xù)更新中救巷。壶熏。。
參考:《R數(shù)據(jù)可視化手冊》浦译、學術(shù)數(shù)據(jù)分析及可視化
1. 理解數(shù)據(jù)與圖層
library(ggplot2)
set.seed(999)
diamonds <- diamonds[sample(1:53940, 5000, replace = F),]
#數(shù)據(jù)寫在底層棒假,則對后續(xù)所有圖層有效
ggplot(diamonds, aes(carat, price, color = cut)) +
geom_point(shape = 18)
#數(shù)據(jù)寫在單一圖層在,則只對該圖層有效
ggplot() +
geom_point(data = diamonds, aes(carat, price, color = cut), shape = 18)
數(shù)據(jù)在初始圖層
ggplot()
中定義時精盅,對后續(xù)所有圖層有效帽哑,當多組數(shù)據(jù)時,可在每個圖層分別定義數(shù)據(jù)
2. 簡單散點圖
library(ggplot2)
library(tidyr)
df <- iris
#修改表頭
colnames(df) <- c('SepalL','SepalW','PetalL','PetalW','Species')
#寬數(shù)據(jù)變長數(shù)據(jù)
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')
- 映射給顏色或大小的變量是分類變量時述么,則是對數(shù)據(jù)進行分組;若映射的是連續(xù)性變量愕掏,則是一個漸變過程度秘。
scale_shape_manual()
和scale_color_brewer
函數(shù)可以后續(xù)自定義圖形和顏色。scale_color_brewer()
調(diào)色盤選擇: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)
##若要虛化擬合線,需要換一個函數(shù)
##geom_line(stat = 'smooth', method = 'lm', se = F,
## color = 'red', size = 2, linetype = 6, alpha = .2)
- 可選的形狀和線型:
形狀和線型color
參數(shù)設置在aes()
之外滑潘,則所有的變量都設置成一個顏色阻荒,而在aes()
之內(nèi),會給不同的因子或者數(shù)值上色- 模型除了
y ~ x
之外众羡,也可以用y ~ log(x)
、y ~ poly(x, 2)
蓖租、y ~ poly(x, 3)
等多項式
3.2 添加新構(gòu)建模型的擬合線
思路:首先創(chuàng)建回歸模型粱侣,然后根據(jù)模型計算變量和預測值的大小,最后繪制回歸線即可蓖宦。
library(ggplot2)
library(gcookbook)
rm(list=ls())
#用lm()函數(shù)創(chuàng)建回歸模型
model <- lm(heightIn ~ ageYear + I(ageYear^2), heightweight)
#創(chuàng)建包含變量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. 繪制兩組來自不同數(shù)據(jù)的點圖
library(tidyr)
library(ggplot2)
df <- iris
head(df)
#修改表頭
colnames(df) <- c('SpealL', 'SpepalW', 'PetalL', 'PetalW', 'Species')
#寬數(shù)據(jù)變長數(shù)據(jù)
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))
繪制多組不同數(shù)據(jù)時
ggplot()
不接任何參數(shù),后續(xù)繪圖函數(shù)調(diào)用參數(shù)data =
分別指明具體的數(shù)據(jù)名稠茂。
5. 氣泡圖
ggplot(mtcars, aes(wt, mpg, color = factor(cyl)))+
#將cyl影射給大小
geom_point(aes(size = cyl))+
#添加坐標
scale_size(breaks = c(4,6,8))