绘制具有多种美学的 ggplot 时,这种情况经常发生,所有这些都引用一个变量。然后,要更改常见的图例标题,我知道的简单方法是使用
labs()
或 guides()
来实现所有常见的美学。
例如
ggplot(data = mtcars, aes(x = mpg, y = wt,
color = factor(am), shape= factor(am), linetype=factor(am), fill=factor(am))) +
geom_point() + geom_smooth() +
labs(color="long legend title", shape="long legend title", linetype="long legend title", fill="long legend title")
有什么方法可以不重复代码中所有常见的美学
"long legend title"
?
您可以创建一个guide_legends列表并将其与!!!在guides()函数中使用它:
这可能对你有用:
library(ggplot2)
library(purrr)
aesthetics <- c("colour", "shape", "linetype", "fill")
# Guides provided to `guides()` must be named.
names(aesthetics) <- aesthetics
guide_legends <- map(aesthetics, ~ guide_legend("long legend title"))
ggplot(data = mtcars,
aes(x = mpg, y = wt,
color = factor(am),
shape= factor(am),
linetype=factor(am),
fill=factor(am))) +
geom_point() +
geom_smooth() +
guides(!!!guide_legends)
)