ggplot2编写函数来绘图

本节来介绍如何编写函数来进行数据可视化,平时画图时我们经常会发现需要编写许多重复的代码来进行绘图,这样不仅使代码冗余也大大降低了代码的可阅读性,因此掌握如何编写函数来简化代码就显得尤为重要,下面通过企鹅数据集来进行一个简单小案例的演示

加载R包

library(tidyverse)
library(glue)
library(palmerpenguins)

使用企鹅数据集其中一个企鹅物种来绘制图

penguins %>%
  filter(species == "Gentoo") %>%
  ggplot() +
  aes(bill_length_mm, body_mass_g, color=sex) +
  geom_point() +
  ggtitle("Species: Gentoo") +
  xlab("bill length (mm)") +
  ylab("body mass (g)") +
  theme(plot.title.position = "plot")

如果想为不同的企鹅物种绘制了一个图。除了filter & ggtitle 函数处理的内容外,其他代码几乎相同

penguins %>%
  filter(species == "Chinstrap") %>%
  ggplot() +
  aes(bill_length_mm, body_mass_g, color=sex) +
  geom_point() +
  ggtitle("Species: Chinstrap") +
  xlab("bill length (mm)") +
  ylab("body mass (g)") +
  theme(plot.title.position = "plot")

我们用感兴趣的物种定义新变量"species_choice"

species_choice <- "Adelie"
penguins %>%
  filter(species == species_choice)
species <- "Adelie"

使用.data访问数据中的物种变量,使用.env访问当前环境中的物种变量

penguins %>%
  filter(.data$species == .env$species)

.data$species为我们获取数据框中的列,而.env$species是我们刚刚创建的本地环境中的变量

现在让我们来编写一个小函数,将物种名称作为输入并绘制图。使用glue来获取我们需要的变量名称

make_plot <- function(species) {
  penguins %>%
    filter(.data$species == .env$species) %>%
    ggplot() +
    aes(bill_length_mm, body_mass_g, color=sex) +
    geom_point() +
    ggtitle(glue("Species: {species}")) +
    xlab("bill length (mm)") +
    ylab("body mass (g)") +
    theme(plot.title.position = "plot")
}

我们可以调用该函数来绘制单个物种的图

make_plot("Adelie")

现在我们可以轻松地为所有物种制作图,而不是重复的粘贴代码。使用map函数获取species中的每个元素并将其用作 make_plot() 的输入,结果图作为列表存储在变量中

species <- c("Adelie", "Chinstrap", "Gentoo")
plots <- map(species, make_plot)

现在我们可以从列表中获取图表,使用以下代码获取图表

plots[[1]]
plots[[2]]
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容