ggplot2, plotly, lattice, RGL, Dygraphs, Leaflet, Highcharter, Patchwork, gganimate, ggridges

ggplot2 Wilkinson 1999,《图形语法》。Wickham 2006,ggplot。可以为图表添加或移除不同层次的细节。

ggplot2 的优势

ggplot2 数据可视化备忘单

  • 美学映射(Aesthetics)
  • 几何对象(Geoms)
  • 分面(Facets)
  • 标签与注释(Labels and annotations)

美学映射(Aesthetic)

美学映射指的是图表中对象的视觉属性。

library(ggplot2)
library(palmerpenguins)

ggplot(data = penguins) + 
  geom_point(mapping = aes(x = flipper_length_mm, y = body_mass_g))

几何对象(Geom)

用于表示数据的几何对象。

分面(Facets)

可以用来展示数据的子集或小组。

标签与注释(Labels and Annotations)

可以用于自定义图表的标题、标签等。

ggplot(data = penguins) + 
  geom_point(mapping = aes(x = flipper_length_mm, y = body_mass_g, color = species)) +
  facet_wrap(~species) + 
  labs(title = "Palmer Penguins 体重与鳍长的关系")

映射(Mapping)

将数据中特定的变量映射到特定的美学属性。

ggplot(data = penguins) + 
  geom_point(mapping = aes(x = bill_length_mm, y = bill_depth_mm))

R 语言区分大小写

library(tidyverse)
glimpse(penguins)
## Rows: 344
## Columns: 8
## $ species           <fct> Adelie, Adelie, Adelie, Adelie, Adelie, Adelie, Adel…
## $ island            <fct> Torgersen, Torgersen, Torgersen, Torgersen, Torgerse…
## $ bill_length_mm    <dbl> 39.1, 39.5, 40.3, NA, 36.7, 39.3, 38.9, 39.2, 34.1, …
## $ bill_depth_mm     <dbl> 18.7, 17.4, 18.0, NA, 19.3, 20.6, 17.8, 19.6, 18.1, …
## $ flipper_length_mm <int> 181, 186, 195, NA, 193, 190, 181, 195, 193, 190, 186…
## $ body_mass_g       <int> 3750, 3800, 3250, NA, 3450, 3650, 3625, 4675, 3475, …
## $ sex               <fct> male, female, female, NA, female, male, female, male…
## $ year              <int> 2007, 2007, 2007, 2007, 2007, 2007, 2007, 2007, 2007…

映射到新的美学参数

ggplot(data = penguins) + 
  geom_point(mapping = aes(x = flipper_length_mm, y = body_mass_g, color = species))

ggplot(data = penguins) + 
  geom_point(mapping = aes(x = flipper_length_mm, y = body_mass_g, shape = species))

点的美学属性(Aesthetics for points)

常见几何对象(Geom functions)

ggplot(data = penguins) + 
  geom_smooth(mapping = aes(x = flipper_length_mm, y = body_mass_g))

条形图示例

ggplot(data = diamonds) +
  geom_bar(mapping = aes(x = cut, fill = clarity))

分面(Facets)

ggplot(data = penguins) + 
  geom_point(mapping = aes(x = flipper_length_mm, y = body_mass_g, color = species)) +
  facet_wrap(~species)

注释(Annotate)

ggplot(data = penguins) + 
  geom_point(mapping = aes(x = flipper_length_mm, y = body_mass_g, color = species)) +
  labs(title = "Palmer Penguins: 体重与鳍长的关系", subtitle = "按物种分组的散点图", caption = "数据由 Dr. Kristen Gorman 收集") +
  annotate("text", x = 220, y = 3500, label = "Gentoo 企鹅最大", fontface = "bold", size = 4.5, angle = 25)

保存图表