R语言 ggplot绘制因子子集时图例的顺序

n53p2ov0  于 2023-02-17  发布在  其他
关注(0)|答案(1)|浏览(147)

通常,图例中项目的顺序可通过使用因子并确保级别按所需顺序进行控制。例如,在下面的代码中,此操作完全按预期方式工作,但在最后一个图中除外,在该图中图例的顺序不正确(例如,它从期望的顺序-1.1,-0.9,0切换到字母顺序,而不是期望的顺序-0.9,-1.1,0)。有哪些方法可以解决这个问题?另外,它是一个bug吗?

library(dplyr)
library(ggplot2)

Z <- tibble(x = c(-1.11, -0.9,  0), x_fct = factor(x)) # Note: factor levels are in correct (i.e., numerical) order

Z |> # Legend in correct order (but no 'circle filled' yet)
  ggplot(aes(x, x, color = x_fct)) +
  geom_point() 

Z |> # Legend is in correct order but `geom_poin()` is obscured by 'circle filled'
  ggplot(aes(x, x, color = x_fct)) +
  geom_point() +
  geom_point(shape = 'circle filled', size = 10, fill='grey', data = ~ . |> filter(x > min(x)))

Z |> # Legend in correct order
  ggplot(aes(x, x, color = x_fct)) +
  geom_point(shape = 'circle filled', size = 10, fill='grey', data = ~ . |> filter(TRUE)) + # `data=...` just to mirror above
  geom_point() 

Z |> # Legend in INCORRECT order
  ggplot(aes(x, x, color = x_fct)) +
  geom_point(shape = 'circle filled', size = 10, fill='grey', data = ~ . |> filter(x > min(x))) +
  geom_point()
nfg76nw0

nfg76nw01#

我刚刚注意到下面的答案:https://stackoverflow.com/a/52560667/239838
基于此,工作解决方案为:

Z |> # Legend in correct order
  ggplot(aes(x, x, color = x_fct)) +
  geom_point(shape = 'circle filled', size = 10, fill='grey', data = ~ . |> filter(x > min(x))) +
  geom_point() +
  scale_color_discrete(drop = FALSE)

我怀疑这是处理这件事的预期方式。

相关问题