既然数字“legend.position”参数已被弃用,我如何才能很好地控制 ggplot 图例的位置?

问题描述 投票:0回答:1

为了最大化 ggplot 图中数据的空间,我想堆叠 y 轴标题(为了可访问性而水平旋转)和图例。到目前为止,使用

legend.position
已经可以实现这一点。例如:

ggplot(iris, aes(Sepal.Length, Petal.Width, shape = Species, colour = Species)) +
  geom_point() +
  theme(axis.title.y = element_text(angle = 0, vjust = 0.9),
        legend.position = c(-0.15, 0.2))

生产: ggplot 图表,图例位于 y 轴标题正下方

但现在我开始使用 ggplot 3.5.0,我收到消息“警告:

legend.position
中的数字
theme()
参数在 ggplot2 3.5.0 中已弃用。”

因此,我一直在尝试使用有关 ggplot 图例的最新官方指南,为我的代码生成一个未弃用的替代方案,但没有成功。例如:

ggplot(iris, aes(Sepal.Length, Petal.Width, shape = Species, colour = Species)) +
  geom_point() +
  theme(axis.title.y = element_text(angle = 0, vjust = 0.9),
        legend.position = "left", 
        legend.justification.left = "bottom")

生成一个图表,其中图例位于 y 轴标题的下方和左侧,而不是直接位于下方: ggplot 图的图例位于 y 轴标题的下方和左侧,而不是直接位于其下方

r ggplot2
1个回答
0
投票

要实现“旧”行为,请设置

legend.position="inside"
并使用
legend.position.inside
传递用于图例放置的数字向量。

下面的代码使用

patchwork
来比较新旧方式:

library(ggplot2)

p1 <- ggplot(iris, aes(Sepal.Length, Petal.Width, shape = Species, colour = Species)) +
  geom_point() +
  theme(
    axis.title.y = element_text(angle = 0, vjust = 0.9),
    legend.position = c(-0.15, 0.2)
  )
#> Warning: A numeric `legend.position` argument in `theme()` was deprecated in ggplot2
#> 3.5.0.
#> ℹ Please use the `legend.position.inside` argument of `theme()` instead.
#> This warning is displayed once every 8 hours.
#> Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
#> generated.

p2 <- ggplot(iris, aes(Sepal.Length, Petal.Width, shape = Species, colour = Species)) +
  geom_point() +
  theme(
    axis.title.y = element_text(angle = 0, vjust = 0.9),
    legend.position = "inside",
    legend.position.inside = c(-0.15, 0.2)
  )

library(patchwork)

p1 / p2

© www.soinside.com 2019 - 2024. All rights reserved.