如何使用 purrr(管道、地图、imaps)将 df 或 tibble 中的两列组合绘制为 R 中的散点图

How can I plot two column combinations from a df or tibble as a scatterplot in R using purrr (pipes, maps, imaps)

我正在尝试为列创建所有组合的散点图:insulinsspgglucose(mclust,糖尿病数据集,在 R 中)class 作为颜色 (u)r。我的意思是胰岛素与 sspg、胰岛素与葡萄糖和 sspg 与葡萄糖。

我想用 tidyverse、purrr、映射和管道操作来做到这一点。我不太了解它,因为我对 R 和函数式编程还比较陌生。

当我加载数据时,我得到了以下列:class、葡萄糖、胰岛素和 sspg。我还使用 pivot_longer 获取列:attr 和 value 但我无法绘制它并且不知道如何创建组合。

我假设最后会有一个 iwalk()map2() 函数,我可能不得不使用 group_by()nest(),也许 combn(., m=2) 用于组合或类似的东西。但它可能会有一些我自己看不到的更简单的解决方案。

我的尝试是这样的:

library(mclust) 
library(dplyr) 
library(tibble)
data(diabetes)

diabTib <- tibble::as_tibble(diabetes)

plot <- diabTib %>%  
  pivot_longer(cols = !c(class), names_to = "attr", values_to = "value") %>% 
  group_by(attr) %>% 
  nest() 

最后,当我执行绘图时或在管道期间作为副作用(?),屏幕上应该有三个绘图(?)。

不胜感激。

library(mclust)
#> Package 'mclust' version 5.4.7
#> Type 'citation("mclust")' for citing this R package in publications.
library(tidyverse)
data("diabetes")

有很多方法可以做到这一点,我可能会从这种方式开始,因为它更容易理解,而且你得到的图和组合的数量一样多

tbl <- tibble::as_tibble(diabetes)
combn(setdiff(names(tbl),"class"),2, simplify = F) %>% #get combinations as vectors
  map(~ggplot(tbl, aes_string(.x[[1]], .x[[2]], color = "class")) + geom_point())
#> [[1]]

#> 
#> [[2]]

#> 
#> [[3]]

如果您想绘制所有组合但在一个图中,则需要 tidyr。 这就是我的计算方式

tbl2 <- tbl %>%
  pivot_longer(cols = -class, names_to = "attr", values_to = "value") %>%
  nest_by(attr) %>% {
    d <- tidyr::expand(., V1 = attr, V2 = attr) # expand combinations
    #rename the nested data to avoid naming conflicts
    d <- left_join(d, mutate(., data = list(rename_with(data, .fn = ~paste0(.x,"_x")))), by = c("V1"="attr"))
    d <- left_join(d, mutate(., data = list(rename_with(data, .fn = ~paste0(.x,"_y")))), by = c("V2"="attr"))
    d
  } %>%
  unnest(c(data.x, data.y))

ggplot(tbl2, aes(x = value_x, y = value_y, color = class_x)) +
  geom_point() +
  facet_grid(rows = vars(V1), cols = vars(V2))

reprex package (v2.0.0)

于 2021 年 6 月 15 日创建

你实际上可以很容易地用 base::plot 得到这个。

# load data
diabetes <- mclust::diabetes 

# define vector of colors based on class in order of cases in dataset
colors <- c("Red", "Green", "Blue")[diabetes$class]

# make pair-wise scatter plot of desired variables colored based on class
plot(diabetes[,-1], col = colors)

reprex package (v2.0.0)

于 2021-06-15 创建