首页 > 解决方案 > 在 ggplot 中添加多个形状图例并叠加形状

问题描述

我正在尝试创建一个易于理解的 ggplot 图,其中 3 个子组由 geom_point 1)颜色(3 种颜色;用于 A、B 和 C 变量),2)整体形状(3 种带边框的彩色形状;用于 c、d 和e 标准),以及 3)覆盖在点上的十字形(2 组;一些有形状覆盖,一些没有基于 df$Subscale = 1 vs. 0)。

我很难弄清楚如何将美学和一个单独的传说结合起来。3,因为那将代表第二种基于形状的美学。

这是我到目前为止所拥有的:带有前 2 个子组的图

这些子组看起来没问题(除了颜色图例还没有工作)。接下来,我想使用 df$Subscale(例如,A_1、C2_1、B_2 而不是 A、C、B2)为名称中带有下划线的变量名称(y 轴)覆盖所有点的形状。由于我已经在使用形状美学,我不知道如何有条件地重新应用形状。

我想应用的形状示例:当我希望它仅应用于某些点时,覆盖应用于所有点

以下是示例数据集 df 的代码:

#The way my data is currently structured

a<- c("A", "A_1", "A_2", "A_3", "A2", "A2_1", "A2_2",
              "B", "B_1", "B_2", "B2", "B2_1",
              "C", "C_1", "C_2", "C2", "C2_1")
b<- c(rep(1, times=4),
            rep(2, times = 3),
            rep(1, times = 3),
            rep(2, times = 2),
            rep(1, times = 3),
            rep(2, times = 2))
col<- c(rep(1, times=7),
      rep(2, times = 5),
      rep(3, times = 5))
u <- c(0, rep(1, times=3),
       0, rep(1, times = 2),
       0, rep(1, times = 2),
      0, rep(1, times = 1),
      0, rep(1, times = 2),
      0, rep(1, times=1))
set.seed(12)
c <- round(rnorm(17, .5, 1),2)
d <- round(rnorm(17, .0, .5),2)
e <- round(rnorm(17, -.2, .5),2)

dat<-data.frame(cbind(a, b, col, u, c, d, e))

#Restructuring for graphing

library(reshape)
df <- melt(dat, id.vars = c("a", "b", "col", "u"))
colnames(df) <- c("Name", "Type", "Color", "Subscale", "Criteria", "Value")
df$Value<- as.numeric(as.character(df$Value))
df$Name_order <- factor(df$Name, levels=df$Name[order(df$Value[df$Criteria == "c"])], ordered=TRUE)

以下是创建图表的代码:

    palette <- c("#56B4E9",  "#D55E00","#009E73")
   graph_test <- ggplot(df, aes(x=df$Value, y = df$Name_order, 
                      colour = df$Color, shape = df$Criteria)) +
  geom_point(size = 6, aes(#colour=factor(df$Color),
                           fill=factor(df$Color),
                           shape=factor(df$Criteria))) + 
  scale_shape_manual(values=c(21, 24, 22),
                     labels=c("Criteria1", "Criteria2", "Criteria3")) +
  scale_fill_manual(values=palette,
                    labels = "c", "d", "e") +
  scale_color_manual(values=c(rep("black", times = 3)))  +
  labs(fill = "ABC", shape = "Criteria") 

#First graph
graph_test

#Second graph
graph_test + geom_point(size = 5, shape=3)

我考虑了形状 aes 的 6 个类别,但我仍然需要有条件地覆盖十字形状,并且我更喜欢 3 个图例(3 种颜色、3 种形状、2 个有覆盖与不覆盖)。

df$CriteriabySub <- paste0(df$Criteria, df$Subscale)

有什么想法/提示可以正确地将十字形应用于某些点并为其创建第三个图例?

标签: rggplot2

解决方案


推荐阅读