首页 > 解决方案 > ggplot:在具有不同类别组合的图中使用相同的形状/颜色

问题描述

我有许多情节,其中出现了不同的类别组合。例如,情节 1 有类别 A、B、D 情节 2 有 A、C、D,情节 3 有 A、B、C、D。我怎样才能告诉 ggplot 对相同的类别使用相同的形状和颜色每个情节?

我的设置基本上是这样的:

df1 <- as.data.frame(cbind(sample(4), sample(4), c("A", "A", "B", "D")))
df2 <- as.data.frame(cbind(sample(4), sample(4), c("B", "C", "C", "D")))
df3 <- as.data.frame(cbind(sample(4), sample(4), c("A","B", "C", "D")))

df.lst <- list(df1, df2, df3)

plt.lst <- list()

for(df in df.lst){

     plt <- ggplot(df, aes(x=V1, y=V2, color=V3, shape=V3)) +
         geom_point()

     plt.lst[[length(plt.lst)+1]] <- plt
}

grid.arrange(grobs=plt.lst)

这给了我不同形状/颜色的相同类别:(

标签: rggplot2

解决方案


概述

使用@markus 的建议,df在创建 3x1 绘图之前将所有数据框绑定到一个中(由 提供facet_wrap())将允许您在具有不同类别组合的绘图中看到相同的形状/颜色。

小面包裹的 SS

代码

# load necessary package -------
library(tidyverse)

# collapse individual data frames into one --------
# so that your data is tidy
df <-
  list(df1 = data.frame(cbind(sample(4), sample(4), c("A", "A", "B", "D")))
       , df2 = data.frame(cbind(sample(4), sample(4), c("B", "C", "C", "D")))
       , df3 = data.frame(cbind(sample(4), sample(4), c("A","B", "C", "D")))) %>%
  bind_rows(.id = "origin")

# create a 3x1 plot -------
df %>%
  ggplot(aes(x = X1, y = X2, color = X3, shape = X3)) +
  geom_point() +
  facet_wrap(facets = vars(origin), nrow = 3, ncol = 1)

# end of script #

推荐阅读