主题的灵活性

使用 ggplot2 进行数据可视化入门

Rick Scavetta

Founder, Scavetta Academy

使用主题的方式

  1. 从零开始(上个视频)
使用 ggplot2 进行数据可视化入门

使用主题的方式

  1. 从零开始(上个视频)
  2. 主题图层对象
  3. 内置主题
    • ggplot2 或 ggthemes 包
  4. 其他包的内置主题
  5. 更新/设置默认主题
使用 ggplot2 进行数据可视化入门

定义主题对象

  • 适用于大量图形
  • 保持风格一致
  • 全局应用特定主题
使用 ggplot2 进行数据可视化入门

定义主题对象

z <- ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) + 
  geom_jitter(alpha = 0.6) +
  scale_x_continuous("Sepal Length (cm)", limits = c(4,8), expand = c(0,0)) +
  scale_y_continuous("Sepal Width (cm)", limits = c(1.5,5), expand = c(0,0)) +
  scale_color_brewer("Species", palette = "Dark2", labels = c("Setosa", "Versicolor", "Virginica"))

使用 ggplot2 进行数据可视化入门

定义主题对象

z + theme(text = element_text(family = "serif", size = 14),
          rect = element_blank(),
          panel.grid = element_blank(),
          title = element_text(color = "#8b0000"),
          axis.line = element_line(color = "black"))

使用 ggplot2 进行数据可视化入门

定义主题对象

theme_iris <- theme(text = element_text(family = "serif", size = 14),
          rect = element_blank(),
          panel.grid = element_blank(),
          title = element_text(color = "#8b0000"),
          axis.line = element_line(color = "black"))
使用 ggplot2 进行数据可视化入门

复用主题对象

z + theme_iris

使用 ggplot2 进行数据可视化入门

复用主题对象

m <- ggplot(iris, aes(x = Sepal.Width)) + 
    geom_histogram(binwidth = 0.1,
                   center = 0.05)
m                 

使用 ggplot2 进行数据可视化入门

复用主题对象

m +
  theme_iris

使用 ggplot2 进行数据可视化入门

复用主题对象

m + 
  theme_iris +
  theme(axis.line.x = element_blank())

使用 ggplot2 进行数据可视化入门

使用主题的方式

  1. 从零开始(上个视频)
  2. 主题图层对象
  3. 内置主题
    • ggplot2 或 ggthemes 包
  4. 其他包的内置主题
  5. 更新/设置默认主题
使用 ggplot2 进行数据可视化入门

使用内置主题

使用 theme_*() 函数访问内置主题。

z + 
  theme_classic()

使用 ggplot2 进行数据可视化入门

使用内置主题

使用 theme_*() 函数访问内置主题。

z + 
  theme_classic() +
  theme(text = element_text(family = "serif"))

使用 ggplot2 进行数据可视化入门

使用主题的方式

  1. 从零开始(上个视频)
  2. 主题图层对象
  3. 内置主题
    • ggplot2 或 ggthemes 包
  4. 来自其他包的内置主题
  5. 更新/设置默认主题
使用 ggplot2 进行数据可视化入门

ggthemes 包

使用 ggthemes 包获取更多函数。

library(ggthemes)
z + 
  theme_tufte()

使用 ggplot2 进行数据可视化入门

使用主题的方式

  1. 从零开始(上个视频)
  2. 主题图层对象
  3. 内置主题
    • ggplot2 或 ggthemes 包
  4. 其他包的内置主题
  5. 更新/设置默认主题
使用 ggplot2 进行数据可视化入门

更新主题

original <- theme_update(text = element_text(family = "serif", size = 14),
                         rect = element_blank(),
                         panel.grid = element_blank(),
                         title = element_text(color = "#8b0000"),
                         axis.line = element_line(color = "black"))
使用 ggplot2 进行数据可视化入门

更新主题

z

使用 ggplot2 进行数据可视化入门

设置主题

theme_set(original)

# Alternatively
# theme_set(theme_grey())

使用 ggplot2 进行数据可视化入门

Vamos praticar!

使用 ggplot2 进行数据可视化入门

Preparing Video For Download...