使用guide_legend()反转传奇

时间:2016-08-25 23:14:27

标签: r ggplot2

我是ggplot2的绝对初学者并且练习使用guide_legend()函数。我不太清楚为什么guide_legend()会颠倒传奇的顺序。

以下是基本示例:

df <- data.frame(x = 1, y = 1:3, z = 1:3)
base <- ggplot(df, aes(x, y)) + geom_raster(aes(fill = z))

这很好地生成了一个栅格图。

但是,当我添加以下行时,图例的顺序会反转。有人可以解释为什么会这样吗?

base + scale_fill_continuous(guide = guide_legend())

我很感激任何想法。无论如何我可以改变订单吗?

由于

添加:我想默认为guide_legend添加reverse = FALSE。我认为reverse=TRUE会修复它,但我不理解重置默认值的重点。我有什么不对的吗?

以下是指南:我指的是http://docs.ggplot2.org/current/guide_legend.html

以下是图片:enter image description here此图片来自网站上方。

1 个答案:

答案 0 :(得分:2)

您的基础图有一个连续的色阶,您可以在图例中看到:

guide="legend"

enter image description here

这会将其转换为离散的色阶,因为设置guide=guide_legend()base + scale_fill_continuous(guide = guide_legend()) 会创建一个离散比例(这是documented in the help):

base

enter image description here

对于连续色标,您可以使用下面的代码,但这不是必需的,因为当颜色变量是连续的时,ggplot默认就是这样做(如{{1}所示情节):

base + scale_fill_continuous(guide = guide_colourbar())

保持离散色标,但反向顺序,以便最高值位于顶部。我还设置了休息符,以便图例中只显示3种颜色:

base + scale_fill_continuous(breaks=1:3, guide=guide_legend(reverse=TRUE))

enter image description here

更新:要解决长评论主题,以下是the ggplot help for guide_legend的三个图。但请注意,第一个实际上并未显示在ggplot帮助页面上;只显示代码。

df <- reshape2::melt(outer(1:4, 1:4), varnames = c("X1", "X2"))

p1 = ggplot(df, aes(X1, X2)) + geom_tile(aes(fill = value))
p2 = p1 + scale_fill_continuous(guide = "legend")
p3 = p1 + scale_fill_continuous(guide = guide_legend())

enter image description here