在主标题上方放置图例

在主标题上方放置图例

本文介绍了在主标题上方放置图例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用theme(legend.position = "top")时,将图例放在ggplot2主标题上方似乎是ggplot早期版本中的默认(也是不需要的)结果:

Placing the legend above the main title in ggplot2 when using theme(legend.position = "top") seemed to be the default (and unwanted) outcome in previous versions of ggplot: ggplot legend at top but below title?

在当前版本的ggplot2中,图例在设置theme(legend.position = "top")时将其自身放置在图和主标题之间.一个小例子:

In the current version of ggplot2, the legend places itself between the plot and the main title when setting theme(legend.position = "top"). A small example:

d <- data.frame(x = 1:2, y = 1:2, z = c("a", "b"))
ggplot(d, aes(x = x, y = y, fill = z)) +
  geom_col() +
  ggtitle("My title") +
  theme(legend.position = "top")

如何将图例放在主标题上方?

How can I place the legend above main title?

推荐答案

library(ggplot2)

ggplot(mtcars, aes(wt, mpg, color=cyl)) +
  geom_point() +
  labs(title = "Hey") +
  theme(plot.margin = margin(t=4,1,1,1, "lines")) +
  theme(legend.direction = "horizontal") +
  theme(legend.position = c(0.5, 1.2))

还有其他方法,但这是我想到的最简单的方法.

There are other ways as well, but this was the easiest one that came to mind.

这篇关于在主标题上方放置图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 00:26