r - 更改堆叠 ggplot 图例中的几何顺序

标签 r ggplot2 legend layer

我正在尝试使用图形的 ggplot 更改图例显示点和线的顺序。

目前,我的图表本身首先显示点,然后在点上方显示线条,这就是我想要的。这是一个可重现的示例:

ggplot(iris, aes(Sepal.Width, Petal.Width, linetype = Species)) +
  geom_point(aes(colour = Species, shape = Species)) +
  geom_smooth()

enter image description here

正如您从图例中看到的,它已经按照绘制的顺序覆盖了值,但我想颠倒这一点。我知道我可以将点叠加在图的顶部,如下所示:

ggplot(iris, aes(Sepal.Width, Petal.Width, linetype = Species)) +
  geom_smooth() +
  geom_point(aes(colour = Species, shape = Species)) 

enter image description here

我已经从 here 中搜索并找到了函数 guides(fill =guide_legend(reverse = TRUE)) ,但这没有效果。

非常感谢任何帮助

最佳答案

根据我在 ggplot descriptions 中读到的内容,我不相信这可以设置覆盖 ggplot 图例的顺序。在 guides 函数中,您可以使用 order 参数设置单独指南的顺序,其解释如下:

"positive integer less that 99 that specifies the order of this guide among multiple guides. This controls the order in which multiple guides are displayed, not the contents of the guide itself. If 0 (default), the order is determined by a secret algorithm."

对我来说,通过以下组合实现您想要的目标似乎最简单:

  1. 使用 legend=FALSE 隐藏某些图例
  2. 多次绘制某些图层。

在下面的示例中,geom_smooth 绘制了两次。一次创建图例背景,然后第二次覆盖数据。第二次绘制时,不显示图例:

ggplot(iris, aes(Sepal.Width, Petal.Width, linetype = Species)) +
  geom_smooth() +
  geom_point(aes(colour = Species, shape = Species)) +
  geom_smooth(show.legend = FALSE)

enter image description here

另一种方法是使线条颜色随每个数据集而变化。这需要更少的尝试并且更容易理解,所以我可能会这样做:

ggplot(iris, aes(Sepal.Width, Petal.Width, colour = Species, shape = Species, linetype = Species)) +
  geom_point(aes())  +
  geom_smooth(aes())

enter image description here

关于r - 更改堆叠 ggplot 图例中的几何顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47663896/

相关文章:

r - 无法将 ggproto 对象添加在一起

r - knitr (R) - 如何不在 HTML 文件中嵌入图像?

r - 用 curl-curly 改变一个变量

r - 如何在ggplot2中转置图例

r - ggplot 图例中的虚线

python - 在不完整/未填充的行中居中 matplotlib 图例条目?

r - 如何在 R 中绘制图例而不绘制符号并且仍然使其很好地对齐?

r - 提交后清除文本输入

r - 在 R 中规范化系统发育树

r - 平滑锯齿状的 geom_segment 看起来像 geom_smooth