R ggplot學習筆記1


R 可視化學習筆記

記參數挺費勁的,還是用的時候查官方文檔吧,現在記個大概就行吧~

1.ggplot2分層次繪圖

1.1 核心理念

  • 把繪圖與數據分離,把數據相關的繪圖與數據無關的繪圖分離,按圖層作圖。ggplot2可以把繪圖拆分成多個圖層,且能夠按照順序創建多重圖形
  • 使用ggplot2包創建圖形時,每個圖形都是由函數ggplot()創建的,提供繪圖的數據和映射
    • 數據(data):數據框對象
    • 映射(mapping):由aes()函數來設置映射

1.2 ggplot2繪圖組件

列幾種常見的部件

  • 幾何對象(geom)

  • 統計變換(stats)

  • 標度(scale)

  • 坐標系(coord)

  • 分面(facet)

  • 主題(theme)

    這些組件之間是通過“+”, 以圖層(layer)的方式來粘合構圖的,可以這樣理解ggplot2中的圖層:每個圖層可以代表一個圖形組件, 這些圖形組件以圖層的方式疊加在一起構成一個繪圖的整體,在每個圖層中的圖形組件又可以分別設定數據、映射或其他相關參數,因此組件之間又是具有相對獨立性的。越后面的圖層越高。
    例如

1.3 data and aes()

數據和映射

ggplot(data = NULL, mapping = aes())

1.3.1 數據

  • data: 用於指定要用到的數據源,必須使數據框類型

1.3.2 aes()

用來設定圖形屬性的

  • mapping:使用aes()函數指定每個變量的角色,除x和y之外的其他參數,例如,size、color、shape等,必須采用name=value的形式。
    -在ggplot中設置的映射是默認映射關系,其他圖層中可以繼承該映射關系,或修改映射關系。也就是說,ggplot設置是全局的,其他圖層可以繼承或者進行修改參考
  • aes()中常見屬性包括
    • x和y:用於指定x軸和y軸的變量
    • color:映射點或線的顏色
    • fill:映射填充區域的顏色
    • linetype:映射圖形的線形(1=實線、2=虛線、3=點、4=點破折號、5=長破折號、6=雙破折號)
    • size:點的尺寸和線的寬度
    • shape:映射點的形狀
    • group:默認情況下ggplot2把所有觀測點分為了一組, 如果需要把觀測點按額外的離散變量進行分組處理, 必須修改默認的分組設置
      • 如果需要把觀測點按指定的因子進行分組處理,必須修改默認的分組設置
      • 分組也可以通過映射把視覺特征(shape、color、fill、size和linetype等)設置為變量來實現分組,分組通常使用因子來實現,這就要求在數據集中存在因子變量,用於對數據分類,實現圖形的分組
        -group設置col區分不同屬性
ggplot(mtcars, aes(wt, mpg,col=cyl)) +
  geom_point(shape=1, size=4)


區分一下col和fill,一個是空心的,一個是實心的,fill是填充嘛
舉個栗子

設置fill區分不同的屬性

ggplot(mtcars, aes(x = wt, y = mpg, fill = cyl)) +
  geom_point(shape = 21, size = 4,alpha=0.6)

factor

若變量是連續型的,則需要將變量離散化,因此factor出現了,否則報錯Error: A continuous variable can not be mapped to shape

ggplot(mtcars, aes(x = mpg, y = qsec, col = cyl, shape = am, size = (hp/wt))) +
  geom_point()

> diamonds
# A tibble: 1,000 x 10
   carat cut       color clarity depth table price     x     y     z
 * <dbl> <ord>     <ord> <ord>   <dbl> <dbl> <int> <dbl> <dbl> <dbl>
 1  0.31 Ideal     G     VS1      62.4    55   802  4.35  4.33  2.71
 2  1.5  Good      G     SI2      64.3    57  8190  7.29  7.2   4.66
 3  0.9  Premium   H     VS2      62.8    58  3810  6.17  6.13  3.86
 4  1.01 Ideal     F     VS2      60.9    58  7411  6.43  6.47  3.93
 5  0.33 Very Good D     VS1      63.2    56  1109  4.45  4.44  2.81
 6  1.08 Ideal     G     VS1      62      55  6779  6.62  6.57  4.09
 7  1.07 Premium   G     SI1      61.6    58  5453  6.6   6.56  4.05
 8  0.33 Premium   H     VS1      59.5    59   743  4.53  4.48  2.68
 9  0.44 Ideal     H     IF       62      57  1255  4.87  4.91  3.02
10  1    Premium   G     VS1      58.6    61  6989  6.57  6.5   3.83
# ... with 990 more rows
# Create the object containing the data and aes layers: dia_plot
dia_plot <- ggplot(diamonds, aes(x = carat, y = price))

# Add the same geom layer, but with aes() inside
dia_plot + geom_point(aes(color = clarity))


放一組對比代碼查看各個參數的作用

# Map cyl to size
ggplot(mtcars, aes(x = wt, y = mpg, size = cyl)) +
  geom_point()

# Map cyl to alpha
ggplot(mtcars, aes(x = wt, y = mpg, alpha = cyl)) +
  geom_point()

# Map cyl to shape 
ggplot(mtcars, aes(x = wt, y = mpg, shape = cyl)) +
  geom_point()

# Map cyl to labels
ggplot(mtcars, aes(x = wt, y = mpg, label = cyl)) +
  geom_text()




1.3.3fill屬性

直接使用fill屬性設置填充,是無效的,若不在aes里面設置color,需要結合fill和子圖層的color,直接在子圖層設置color屬性值,也是無效的,因此需要分組
這里需要復習一下數據處理的的gather函數,由寬面板變為長面板

my_color <- "#4ABEFF"
ggplot(mtcars, aes(x = wt, y = mpg)) +
  geom_point(color = my_color)

# Set the fill aesthetic; color, size and shape attributes
ggplot(mtcars, aes(x = wt, y = mpg, fill = cyl)) +
  geom_point(size = 10, shape = 23, color = my_color)


1.4 geom_xxx() and stat()

1.4.1 geom_xxx

  • 幾何對象控制圖層的渲染和生成的圖像類型,例如,geom_point()會生成散點圖,而geom_line會生成折線圖。
    • 函數ggplot()可以設置圖形,但是沒有視覺輸出,需要使用一個或多個幾何函數向圖形中添加幾何對象(geometric,簡寫為geom),包括點(point)、線(line)、條(bar)等,而添加幾何圖形的格式十分簡單,通過符號“+”把幾何圖形添加到plot中
ggplot()+
geom_xxx()

ggplot2官方文檔geom_xxx

  • geom_text()添加文本
  • geom_bar()條形圖
    • position
      geom_bar()里面的位置調整參數
      -identity(默認)
    • jitter
    • stack 堆疊
    • fill 堆疊顯示百分比
    • dodge 並列
    • posn_d overlab 疊加
  • geom_points() 散點圖==scatter
    舉個栗子
cyl.am + 
geom_bar(position="stack")

# Fill - show proportion
cyl.am + 
  geom_bar(position = "fill")  

# Dodging - principles of similarity and proximity
cyl.am +
  geom_bar(position ="dodge") 

# Clean up the axes with scale_ functions
val = c("#E41A1C", "#377EB8")
lab = c("Manual", "Automatic")
cyl.am +
  geom_bar(position = "dodge") +
  scale_x_discrete("Cylinders") + 
  scale_y_continuous("Number") +
  scale_fill_manual("Transmission", 
                    values = val,
                    labels = lab)




ggplot(mtcars, aes(x = cyl, fill = am)) +
  geom_bar(position = posn_d, alpha = 0.6)
  • geom_histgram 柱狀圖
ggplot(mtcars, aes(mpg)) +
  geom_histogram(aes(y = ..density..), binwidth = 1, fill = "#377EB8")
  • geom_freqpoly 柱狀圖的曲線圖
ggplot(mtcars, aes(mpg, color = cyl)) +
  geom_freqpoly(binwidth = 1)
  • lines
    時間序列圖
  • geom_rect()
ggplot(economics, aes(x = date, y = unemploy/pop)) +
  geom_rect(data = recess,
            aes(xmin = begin, xmax = end, ymin = -Inf, ymax = +Inf),
            inherit.aes = FALSE, fill = "red", alpha = 0.2) +
  geom_line()

1.4.2 geom_xxx常見參數

  • color:對點、線和填充區域的邊界進行着色
  • fill:對填充區域着色
  • alpha:演示的透明度,從透明(0)到不透明(1)
  • linetype:圖案的線條(1=實線、2=虛線、3=點、4=點破折號、5=長破折號、6=雙破折號)
  • size:點的尺寸和線的寬度
  • shape:點的形狀(和par()函數的pch參數相同)
  • position:繪制條形圖和點等對象的位置
    舉個栗子
# Scatter plot: clarity (x), carat (y), price (color)
ggplot(diamonds, aes(x = clarity, y = carat, color = price)) +
  geom_point(alpha = 0.5)

# Dot plot with jittering
ggplot(diamonds, aes(x = clarity, y = carat, color = price)) +
  geom_point(alpha = 0.5, position = "jitter")

設置position之后,明顯看清了,因該是調整了刻度

  • binwidth:分箱的寬度
  • notch:表示方塊圖是否應該有缺口
  • sides:地毯圖的位置("b"=底部、"l"=左部、"r"=右部、"bl"=左下部,等)
  • width:箱線圖的寬度
    label and shape are only applicable to categorical data.

1.4.3 stat

  • 統計變換是對數據進行統計,通常以某種方式對數據信息進行匯總, 例如通過stat_smooth()添加光滑曲線。
  • 每一個幾何對象都有一個默認的統計變換, 並且每一個統計變換都有一個默認的幾何對象

1.4.4 geom_jitter()

在R中散點圖的時候會經常出現,點重合比較嚴重的現象,這對我們尋找數據規律或者觀察數據有很大的干擾。因此R中,可以用geom_jitter()函數來調整,消除點的重合。

geom_jitter(mapping = NULL, data = NULL, stat = "identity", position = "jitter", ..., width = NULL, height = NULL, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE)

就參數而言,geom_jitter()和其他函數差別不大,特別的兩個參數是width,height

  • width 用於調節點波動的寬度
  • height 用於調節點波動的高度

例如有一個散點圖

經過處理之后,明顯不重合了

ggplot(mtcars, aes(x = mpg, y = 0)) +
  geom_jitter()

# 2 - Add function to change y axis limits
ggplot(mtcars, aes(x = mpg, y = 0)) +
  geom_jitter() +
  scale_y_continuous(limits = c(-2,2))#設置y軸起始刻度,這是連續變量刻度


1.5 scale

  • 標度:標度控制着數據到圖形屬性的映射,更重要的一點是標度將我們的數據轉化為視覺上可以感知的東西, 如大小、顏色、位置和形狀。所以通過標度可以修改坐標軸和圖例的參數
    scale

1.5.1常見scale

  • labs()標簽 xlab() ylab() ggtitle()
  • 圖形選項(顏色、size、形狀、線形等)
    自定義圖形選項
    scale_colour_manual()
    scale_fill_manual()
    scale_size_manual()
    scale_shape_manual()
    scale_linetype_manual()
    scale_alpha_manual()
    scale_discrete_manual()
  • 坐標軸
    標度是區分離散和連續變量的,標度用於將連續型、離散型和日期-時間型變量映射到繪圖區域,以及構造對應的坐標軸

1.6 坐標軸

坐標系統確定x和y美學如何組合以在圖中定位元素。默認的坐標系是笛卡爾坐標系,coord_cartesian(),笛卡爾坐標系是最常用的坐標系,函數coord_flip() 用於反轉笛卡爾坐標系,把x軸和y軸對調,一般采用默認的額

1.7 facet

這個參數一開始我不太懂是用來做什么的

facet_grid(rows = NULL, cols = NULL, scales = "fixed",
  space = "fixed", shrink = TRUE, labeller = "label_value",
  as.table = TRUE, switch = NULL, drop = TRUE, margins = FALSE,
  facets = NULL)
  • rows, cols
    A set of variables or expressions quoted by vars() and defining faceting groups on the rows or columns dimension. The variables can be named (the names are passed to labeller).
    For compatibility with the classic interface, rows can also be a formula with the rows (of the tabular display) on the LHS and the columns (of the tabular display) on the RHS; the dot in the formula is used to indicate there should be no faceting on this dimension (either row or column).
    數據框的行列,變量

  • scales

    • "fixed" x和y的標度在所用平面中都相同,在不同分面中進行固定
    • "free_x" 固定x軸,y軸自由變化
    • "free_y" 固定y軸,x軸自由變化
    • "free" x和y的標度在每個版面都可以變化
  • space
    If "fixed", the default, all panels have the same size. If "free_y" their height will be proportional to the length of the y scale; if "free_x" their width will be proportional to the length of the x scale; or if "free" both height and width will vary. This setting has no effect unless the appropriate scales also vary.

  • 可以根據數據的不同分組, 將圖形按照水平或者垂直方向進行分割,同時可以共享x軸或者y軸

  • 分組和刻面都用於對數據分組,便於觀察各自的規律、趨勢和模式,不同的是,分組是把圖形繪制到一個大的圖形中,通過美學特征來區分,而刻面是把圖形繪制到不同的網格中。

  • 刻面是在一個畫布上分布多幅圖形,這一過程需要先把數據划分為多個子集, 然后把每個子集依次繪制到畫布的不同面板中

    • facet_grid()在網格分面
      • 根據數據不同可以繪制共用x軸或者y軸的子圖,python中的subplots,
str(iris.tidy)

# Think about which dataset you would use to get the plot shown right
# Fill in the ___ to produce the plot given to the right
ggplot(iris.tidy, aes(x = Species, y = Value, col = Part)) +
  geom_jitter() +
  facet_grid(. ~ Measure)

> str(iris.tidy)
'data.frame':	600 obs. of  4 variables:
 $ Species: Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...
 $ Part   : chr  "Sepal" "Sepal" "Sepal" "Sepal" ...
 $ Measure: chr  "Length" "Length" "Length" "Length" ...
 $ Value  : num  5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...

  • facet_wrap()將一維面板的絲帶纏繞成二維,封裝分面,自動分成2x4, 3x2等版塊
  • vars()引用分面變量
    具體可以參考

1.8 theme

主題

2 為何使用ggplot

因為省代碼😄hahah~
來一個栗子對比一下

  • 基礎包里面的plot繪圖
# Convert cyl to factor (don't need to change)
mtcars$cyl <- as.factor(mtcars$cyl)

# Example from base R (don't need to change)
plot(mtcars$wt, mtcars$mpg, col = mtcars$cyl)
abline(lm(mpg ~ wt, data = mtcars), lty = 2)
lapply(mtcars$cyl, function(x) {
  abline(lm(mpg ~ wt, mtcars, subset = (cyl == x)), col = x)
  })
legend(x = 5, y = 33, legend = levels(mtcars$cyl),
       col = 1:3, pch = 1, bty = "n")


ggplot繪圖

ggplot(mtcars, aes(x = wt, y = mpg, col = cyl)) +
  geom_point() +
  geom_smooth(method = "lm", se = FALSE) +
  geom_smooth(aes(group = 1), method = "lm", se = FALSE, linetype = 2)

wide函數,將寬面板,變成長面板

# Load the tidyr package
library(tidyr)

# Add column with unique ids (don't need to change)
iris$Flower <- 1:nrow(iris)

# Fill in the ___ to produce to the correct iris.wide dataset
iris.wide <- iris %>%
  gather(key, value, -Species, -Flower) %>%
  separate(key, c("Part","Measure"), "\\.") %>%
  spread(Measure, value)

3 qplot

快速作圖,類似與plot


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM