桑基图:有没有办法根据 ggsankey 中的额外列为流程着色?

Sankey Diagram: is there a way to color the flows according to an extra column in ggsankey?

我正在用 ggalluvial 制作桑基图。

这是我的数据集

library(ggsankey)
library(tidyverse)

df <-
  mtcars %>%
  make_long(cyl, vs, am, gear, carb) %>% 
  mutate(color = c(rep("red", 80), rep("blue", 80)))

您可以获得这样的桑基图:

df %>% 
ggplot(aes(x = x, 
               next_x = next_x, 
               node = node, 
               next_node = next_node,
               fill = factor(node),
           label = factor(node))) +
  geom_sankey()+
  geom_sankey(flow.alpha = .6,
              node.color = "gray30") +
  geom_sankey_label(size = 3, color = "white", fill = "gray40") +
  scale_fill_viridis_d() +
  theme_sankey(base_size = 18) +
  labs(x = NULL) +
  theme(legend.position = "none",
        plot.title = element_text(hjust = .5))

现在,我想根据 df 的列 color 为标签之间的流着色。可能吗?如果没有,您知道在 R 中执行此操作的其他方法吗?

我试过了:

df %>% 
ggplot(aes(x = x, 
               next_x = next_x, 
               node = node, 
               next_node = next_node,
               fill = factor(color),
           label = factor(node))) +
  geom_sankey()+
  geom_sankey(flow.alpha = .6,
              node.color = "gray30") +
  geom_sankey_label(size = 3, color = "white", fill = "gray40") +
  scale_fill_viridis_d() +
  theme_sankey(base_size = 18) +
  labs(x = NULL) +
  theme(legend.position = "none",
        plot.title = element_text(hjust = .5))

但剧情似乎完全崩溃了:

最后,ggaluvial似乎更适合我的问题:

数据格式如下:

df <-
  mtcars %>%
  select(cyl, vs, am, gear, carb) %>% 
  mutate(color = c(rep("red", nrow(mtcars)/2), rep("blue", nrow(mtcars)/2)),
         id = seq(1:nrow(mtcars))) %>% 
  pivot_longer(cols = !c(color, id),
               names_to = "var",
               values_to = "state")

下面是具有正确流线颜色的图:

df %>% 
  ggplot(aes(x = var,
               stratum = state,
               label = state,
               alluvium = id)) +
      stat_alluvium(aes(fill = color),
                    width = 0,
                    alpha = 1,
                    geom = "flow")+
      geom_stratum(width = 0.2)+
      geom_text(stat = "stratum", size = 5, angle = 90)+
      theme_bw()