ggplot2图例移至底部并水平排列

134

我该如何将ggplot2图例移到绘图底部并将其水平显示?

示例代码:

library(reshape2) # for melt
df <- melt(outer(1:4, 1:4), varnames = c("X1", "X2"))
p1 <- ggplot(df, aes(X1, X2)) + geom_tile(aes(fill = value))
p1 + scale_fill_continuous(guide = guide_legend())

期望的(大致)结果: 输入图像描述在这里


6
7年8个月后,我终于弄清楚了如何得到这个问题的期望结果 :) 向下滚动到第二个答案。 - Arthur Yip
2个回答

181

如果您想移动图例的位置,请使用以下代码:

library(reshape2) # for melt
df <- melt(outer(1:4, 1:4), varnames = c("X1", "X2"))
p1 <- ggplot(df, aes(X1, X2)) + geom_tile(aes(fill = value))
p1 + scale_fill_continuous(guide = guide_legend()) +
    theme(legend.position="bottom")
这应该会给你想要的结果。 底部的图例

2
你知道是否可以在底部绘制一个连续的图例条吗?(因此不是在中间带有数字而是在顶部)。谢谢。 - Janvb
3
当前的ggplot会出现警告:'opts'已经被弃用,请使用'theme'代替。(已弃用;最后一次使用版本为0.9.1)。将opts替换为theme即可解决问题。 - krlmlr
是的,我预计ggplot的内部工作方式会发生变化。 - Shreyas Karnik
11
使用已废弃的项目是不好的实践。您可以通过以下方式以完全相同的方式使用它:+ theme(legend.position='bottom') - Omar Wagih
不幸的是,当数字和颜色并排时存在一些歧义;请参见下面我的答案,尝试多次改进此问题。 - Arthur Yip
也可以参考以下链接来避免 ggplot2 图例项之间的间距问题:https://dev59.com/KKzka4cB1Zd3GeqP4zRP#50885122 https://dev59.com/xJ_ha4cB1Zd3GeqPyGd8 https://dev59.com/La3la4cB1Zd3GeqPOYuz https://dev59.com/bloT5IYBdhLWcg3wlgXn。 - Arthur Yip

61

这是创建所需结果的方法:

library(reshape2); library(tidyverse)
melt(outer(1:4, 1:4), varnames = c("X1", "X2")) %>%
ggplot() + 
  geom_tile(aes(X1, X2, fill = value)) + 
  scale_fill_continuous(guide = guide_legend()) +
  theme(legend.position="bottom",
        legend.spacing.x = unit(0, 'cm'))+
  guides(fill = guide_legend(label.position = "bottom"))

这段文字是由reprex package (v0.3.0)于2019年12月7日创建的。


编辑:这些不完美的选项不再需要了,但我会将它们留在这里供参考。

两个不完美的选项,虽然不能完全满足您的要求,但非常接近(至少能将颜色放在一起)。

library(reshape2); library(tidyverse)
df <- melt(outer(1:4, 1:4), varnames = c("X1", "X2"))
p1 <- ggplot(df, aes(X1, X2)) + geom_tile(aes(fill = value))
p1 + scale_fill_continuous(guide = guide_legend()) +
 theme(legend.position="bottom", legend.direction="vertical")

p1 + scale_fill_continuous(guide = "colorbar") + theme(legend.position="bottom")

这段内容是由reprex包 (v0.2.1)于2019-02-28创建的。


虽然从理论上来说这可能回答了问题,但最好在此处包含答案的关键部分,并提供参考链接。 - Rohit Gupta

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接