在主标题上方放置图例

时间:2018-10-12 17:37:13

标签: r ggplot2 legend

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

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

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") 

enter image description here

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

3 个答案:

答案 0 :(得分:6)

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))

enter image description here

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

答案 1 :(得分:4)

与调整边距相比,这需要做更多的工作,但是应该可以更好地控制布局和尺寸。我正在使用cowplot中的函数:get_legend从图中提取图例,然后使用plot_grid创建这两个ggplot元素的网格。

在创建带有图例的图p之后,cowplot::get_legend(p)然后创建一个仅是图例的ggplot对象。使用plot_grid重新放置它们,同时添加一个theme调用,以从p中删除图例。您可能需要调整高度并调整边距。

library(ggplot2)

p <- ggplot(d, aes(x = x, y = y, fill = z)) + 
  geom_col() +
  ggtitle("My title") +
  theme(legend.position = "bottom") 

legend <- cowplot::get_legend(p)

cowplot::plot_grid(
  legend,
  p + theme(legend.position = "none"),
  ncol = 1, rel_heights = c(0.1, 1)
)

reprex package(v0.2.1)于2018-10-12创建

答案 2 :(得分:2)

或者我们可以创建一个假面,并在其中放置情节标题。之后,进行一些调整以删除带状面并减少图例边距

library(ggplot2)

d <- data.frame(x = 1:2, y = 1:2, z = c("a", "b")) 
d$Title <- "My title\n"

# default legend key text
p1 <- ggplot(d, aes(x = x, y = y, fill = z)) + 
  geom_col() +
  facet_grid(~ Title) +
  theme(strip.text.x = element_text(hjust = 0, vjust = 1,
                                    size = 14, face = 'bold'),
        strip.background = element_blank()) +
  theme(legend.margin = margin(5, 0, 0, 0),
        legend.box.margin = margin(0, 0, -10, 0)) +
  theme(legend.position = "top") +
  NULL

# legend key text at the bottom
p2 <- ggplot(d, aes(x = x, y = y, fill = z)) + 
  geom_col() +
  facet_grid(~ Title) +
  theme(strip.text.x = element_text(hjust = 0, vjust = 1,
                                    size = 14, face = 'bold'),
        strip.background = element_blank()) +
  theme(legend.margin = margin(5, 0, 0, 0),
        legend.box.margin = margin(0, 0, -10, 0)) +
  guides(fill = guide_legend(label.position = "bottom",
                             title.position = "left", title.vjust = 1)) +
  theme(legend.position = "top") +
  NULL


library(patchwork)
p1 | p2

reprex package(v0.2.1.9000)于2018-10-12创建