R 如何在ggplot图例行中组织每种颜色的所有形状?

R 如何在ggplot图例行中组织每种颜色的所有形状?,r,ggplot2,R,Ggplot2,对于这样的绘图: df <- structure(list(x = c(-0.951618567265016, -0.0450277248089203, -0.784904469457076, -1.66794193658814, -0.380226520287762, 0.918996609060766, -0.575346962608392, 0.607964322225033, -1.61788270828916, -0.0555619655245394 ), y = c(0.5

对于这样的绘图:

df <- structure(list(x = c(-0.951618567265016, -0.0450277248089203, 
-0.784904469457076, -1.66794193658814, -0.380226520287762, 0.918996609060766, 
-0.575346962608392, 0.607964322225033, -1.61788270828916, -0.0555619655245394
), y = c(0.519407203943462, 0.301153362166714, 0.105676194148943, 
-0.640706008305376, -0.849704346033582, -1.02412879060491, 0.117646597100126, 
-0.947474614184802, -0.490557443700668, -0.256092192198247), 
    color = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 4L
    ), .Label = c("1", "2", "3", "4"), class = "factor"), shape = structure(c(1L, 
    2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L), .Label = c("1", "2", 
    "3"), class = "factor")), class = "data.frame", row.names = c(NA, 
-10L))
g <- ggplot() +
  geom_point(data = df, aes(x = x, y = y, colour = color, shape = shape)) +
  theme(legend.position = "right")

df也许这就是你要找的

  • 起点是只有一个图例。为此,我添加了一个新变量
    shape\u color
    ,作为因子
    color
    shape
    的交互作用

  • color
    shape
    上映射
    shape\u color

  • 为了获得正确的颜色和形状,我们使用了
    scale\u xxx\u手册
    。为此,我用
    颜色和
    形状设置了两个向量

  • 使用参数
    nrow=4
    byrow=TRUE

  • 棘手的部分是标签

    a。为此,我使用了一个helper函数,它将不需要的标签替换为空字符串,即只显示第三个标签,并确保标签中只显示颜色类别

    b。最后,要使第四行的标签也位于右侧,我们必须确保图例中“包含”了空类别。为此,我在两种刻度中都使用arguemnt
    drop=FALSE
    ,以便在图例中包括未使用的级别。但是,我将这些类别的颜色和形状设置为NA,以便它们不可见

  • 库(ggplot2)
    
    df谢谢你的回答,它工作得非常好,尽管我很难概括我的真实数据,比如12个形状和34个颜色lol。可能需要更多地玩转这个想法。

    干得好Stefan。我不认为我会想到这种方法。@AllanCameron感谢Allan。然而,从你所看到的所有伟大的工作来看,我很肯定你会提出类似的解决方案。最好的。