通常,图例中项目的顺序可通过使用因子并确保级别按所需顺序进行控制。例如,在下面的代码中,此操作完全按预期方式工作,但在最后一个图中除外,在该图中图例的顺序不正确(例如,它从期望的顺序-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()
1条答案
按热度按时间nfg76nw01#
我刚刚注意到下面的答案:https://stackoverflow.com/a/52560667/239838
基于此,工作解决方案为:
我怀疑这是处理这件事的预期方式。