更改 ggplot2 图例顺序而不更改手动指定的美学

Change ggplot2 legend order without changing the manually specified aesthetics

我需要制作一个包含多种数据的图表,我正在用线绘制一种数据,一种用点绘制数据。我添加了一个手动指定的图例来显示哪种类型是点,哪种类型是线(诚然,我的方法有点老套),这对图例顺序有效except。这是一个虚拟示例:

DF1 <- data.frame(X = 1:10, 
              Y = c(1:10*0.5, 1:10*0.25),
              Fruit = rep(c("mango", "kiwi"), each = 10))
DF2 <- data.frame(X = 1:10, 
                  Y = c(1:10*2, 1:10*4),
                  Cat = rep(c("tabby", "calico"), each = 10))
Empty <- data.frame(X = mean(DF$X),
                    Y = as.numeric(NA), 
                    # Q = c(0, 1))
                    Type = c("Cat", "Fruit"))
Mygraph <- ggplot(DF1, aes(x = X, y = Y, color = Fruit)) +
    geom_point() + 
    geom_line(data = DF2, aes(x = X, y = Y, linetype = Cat), 
              inherit.aes = F) +
    labs(color = NULL, linetype = NULL) +
    geom_point(data = Empty, aes(x = X, y = Y, alpha = Type),
               inherit.aes = F) +
    geom_line(data = Empty, aes(x = X, y = Y, alpha = Type),
              inherit.aes = F) +
    scale_alpha_manual(
        name = "Type of item", values = c(1, 1),
        breaks = c("Fruit", "Cat"),
        guide = guide_legend(override.aes =
                                 list(linetype = c("blank", "solid"),
                                      shape = c(16, NA)))) +
    theme_bw()
Mygraph

这张图看起来不错:

但请查看当我尝试指定顺序时“项目类型”位发生了什么:

 Mygraph + 
     guides(alpha = guide_legend(order = 1),
            linetype = guide_legend(order = 2),
            color = guide_legend(order = 3))

为什么我指定的美学消失了?我怎样才能既指定图例的那部分应该是什么样子,又指定图例的三个部分的顺序应该是 1.alpha,2.线型,然后是 3.颜色?

您试图在两个地方(即 guides()scale_alpha...())覆盖 alpha 的美学,而 ggplot 选择只解释其中一个。我建议在图例顺序覆盖中包含形状覆盖,如下所示:

library(ggplot2) 

ggplot(DF1, aes(x = X, y = Y, color = Fruit)) +
  geom_point() + 
  geom_line(data = DF2, aes(x = X, y = Y, linetype = Cat),  inherit.aes = F) +
  labs(color = NULL, linetype = NULL) +
  geom_point(data = Empty, aes(x = X, y = Y, alpha = Type), inherit.aes = F) +
  geom_line(data = Empty, aes(x = X, y = Y, alpha = Type), inherit.aes = F) +
  scale_alpha_manual(name = "Type of item", values = c(1, 1), breaks = c("Fruit", "Cat")) +
  guides(alpha = guide_legend(order = 1,
                              override.aes=list(linetype = c("blank", "solid"),
                                                shape = c(16,NA))),
         linetype = guide_legend(order = 2),
         color = guide_legend(order = 3)) +
  theme_bw()

数据:

DF1 <- data.frame(X = 1:10, 
                  Y = c(1:10*0.5, 1:10*0.25),
                  Fruit = rep(c("mango", "kiwi"), each = 10))
DF2 <- data.frame(X = 1:10, 
                  Y = c(1:10*2, 1:10*4),
                  Cat = rep(c("tabby", "calico"), each = 10))
Empty <- data.frame(X = mean(DF1$X),
                    Y = as.numeric(NA), 
                    Type = c("Cat", "Fruit"))