如何在 R 中使用 ggplot 修复图例顺序?

How to fix legend order using ggplot in R?

我正在使用 ggplot2ggnewscale 创建一个包含 2 个图例的情节。我想要实现的是修复单独图例的顺序,以便它们始终以相同的顺序出现。下面的图片和代码显示了我遇到的问题的基本示例。

首先,创建一些数据并设置调色板:

df <- data.frame(x = c(1:5), y = runif(10))
df_1 <- data.frame(x = c(1:5), y = runif(10))

pal_1 = rev(colorspace::sequential_hcl(palette = "Blues 3", n = 10))
pal_2 = rev(colorspace::sequential_hcl(palette = "Reds 3", n = 10))

现在创建一个图(注意我为图例设置的限制在 0 到 1 之间):

library(ggplot2)
library(ggnewscale)

ggplot(df, mapping = aes(x, y)) +
  geom_point(size = 3, aes(fill = y)) +
  scale_fill_gradientn(colors = pal_1, limits = c(0,1), name = "val1") +
  new_scale_fill() +
  geom_point(data = df_1, size = 3, aes(fill = y)) +
    scale_fill_gradientn(colors = pal_2, limits = c(0,1), name = "val2") 

这将产生下图(请注意 val1 的图例在顶部):

现在,如果我们将 val2 的限制更改为更大的值,例如:

ggplot(df, mapping = aes(x, y)) +
  geom_point(size = 3, aes(fill = y)) +
  scale_fill_gradientn(colors = pal_1, limits = c(0,1), name = "val1") +
  new_scale_fill() +
  geom_point(data = df_1, size = 3, aes(fill = y)) +
    scale_fill_gradientn(colors = pal_2, limits = c(0,10), name = "val2") 

我们会得到这个(注意 val2 图例现在位于顶部:

看来ggplot会将极限范围较大的图例放在最上面。我想知道是否有一种方法可以修复图例顺序,例如 val1 始终位于顶部...无论限制范围如何?

您可以通过 guide_xxxorder 参数指定图例的顺序:

df <- data.frame(x = c(1:5), y = runif(10))
df_1 <- data.frame(x = c(1:5), y = runif(10))

pal_1 = rev(colorspace::sequential_hcl(palette = "Blues 3", n = 10))
pal_2 = rev(colorspace::sequential_hcl(palette = "Reds 3", n = 10))

library(ggplot2)
library(ggnewscale)

ggplot(df, mapping = aes(x, y)) +
  geom_point(size = 3, aes(fill = y)) +
  scale_fill_gradientn(colors = pal_1, limits = c(0,1), name = "val1", 
                       guide = guide_colorbar(order = 1)) +
  new_scale_fill() +
  geom_point(data = df_1, size = 3, aes(fill = y)) +
  scale_fill_gradientn(colors = pal_2, limits = c(0,10), name = "val2",
                       guide = guide_colorbar(order = 2))