在ggplot2中并排横向图例 [英] Side by side horizontal legends in in ggplot2

查看:3615
本文介绍了在ggplot2中并排横向图例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想让我的ggplot图例并排显示,在符号上方的变量名称下面,因为它们位于



您可以使用 title.hjust像我在问题中所建议的那样将标题转移到中心= 0.5 。但是,经过检查,这样做可能会让读者误解哪些颜色/点指向哪个变量。


I would like to get my ggplot legends to appear side by side, underneath the plot with the variable names above the symbols, as they are in this blog post (the second plot). The opts function is now defunct, and theme does not appear to replicate its behaviour...

library("ggplot2")
ggplot(diamonds, aes(x = carat, y=price, shape = cut, group=interaction(cut, color), color=color)) +
geom_point() +
#opts(legend.direction = "horizontal", legend.position = "bottom")
#potential options, not all seem have an effect...
theme(legend.direction = "horizontal") +
theme(legend.position = "bottom") +
theme(legend.box = "vertical") +
theme(legend.title.align = 0)

...using my MS paint skills to illustrate the desired plot.

解决方案

Adapting from the previous suggestions with legend.box = "horizontal", I have found that you can get the legend titles on top using title.position = "top" in the guides for the scale_ functions. These have to be defined for each variable that makes up the legend else the title will be to the left.

ggplot(data = diamonds, 
       mapping = aes(x = carat, y = price, shape = cut,
                     group=interaction(cut, color), color=color)) +
  geom_point() +
  theme(legend.box = "horizontal",
        legend.position="bottom") +
  scale_shape(guide = guide_legend(title.position = "top")) +
  scale_colour_discrete(guide = guide_legend(title.position = "top", nrow = 1))

You could shift the titles to the center, as I suggested in the question, using title.hjust = 0.5. However, upon inspection, doing so might confuse the reader as to which colours/points refers to which variable.

这篇关于在ggplot2中并排横向图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆