如何在 ggplot2 中的图例周围添加一个框?

How to add a box around the legend in ggplot2?

使用以下脚本,如何添加如下图所示的底部图例框?

start <- c('2002 Q1', '2008 Q4')
end <- c('2003 Q3', '2011 Q2')

dates <- as.yearqtr(seq(as.Date('2002-01-01'), as.Date('2019-06-01'), by='quarter'))

cod <- tibble(start = as.yearqtr(start), end = as.yearqtr(end)) %>%
  filter(start %in% dates) %>%
  mutate(start = as.Date(start)) %>%
  mutate(end = as.Date(end))

dates <- as.Date(dates)

tbl_fz <- tibble(x = dates, fz = 0.5)

plot <- ggplot(data = tbl_fz) +
  geom_rect(data = cod, aes(xmin = start, xmax = end,
                            ymin = 0, ymax = 1, fill = "b"), alpha = 0.9) +
  geom_line(aes(x = x, y = fz), size = 0.5) + 
  ggtitle('') + 
  theme_classic() +
  theme(title = element_text(size = 8),
        plot.title = element_text(hjust = 0.5),
        legend.position = c(0.5, -0.5)) +
  ylab('') +
  xlab('') +
  scale_x_date(date_breaks = '2 year', date_labels = '%Y',
               expand = c(0, 0)) + 
  scale_y_continuous(expand = c(0,0)) +
  scale_fill_manual(name = 'kkkk',
                    values = c('grey'),
                    labels = c('kkkk'))

plot

这可以这样实现。为了将图例放在底部,我建议 使用 legend.position = "bottom"。要将线添加到图例中,请在 color aes 上映射一些内容并使用 scale_color_manual,就像您对 fill aes 所做的那样。要在图例周围使用方框,请使用 legend.box.background = element_rect(color = "black")。由于框被部分覆盖,我还在顶部和左侧添加了一些边距。最后,为了获得正确的图例顺序,例如要获得更粗的线条,您可以使用 guide_legend 来设置图例的样式。

# Packages ----------------------------------------------------------------
library(dplyr)
library(ggplot2)
library(zoo)


start <- c('2002 Q1', '2008 Q4')
end <- c('2003 Q3', '2011 Q2')

dates <- as.yearqtr(seq(as.Date('2002-01-01'), as.Date('2019-06-01'), by='quarter'))

cod <- tibble(start = as.yearqtr(start), end = as.yearqtr(end)) %>%
  filter(start %in% dates) %>%
  mutate(start = as.Date(start)) %>%
  mutate(end = as.Date(end))

dates <- as.Date(dates)

tbl_fz <- tibble(x = dates, fz = 0.5)

plot <- ggplot(data = tbl_fz) +
  geom_rect(data = cod, aes(xmin = start, xmax = end,
                            ymin = 0, ymax = 1, fill = "b"), alpha = 0.9) +
  geom_line(aes(x = x, y = fz, color = "c"), size = 0.5) + 
  ggtitle('') + 
  theme_classic() +
  theme(title = element_text(size = 8),
        plot.title = element_text(hjust = 0.5),
        legend.position = "bottom",
        legend.box.background = element_rect(color = "black"),
        legend.box.margin = margin(t = 1, l = 1)) +
  scale_x_date(date_breaks = '2 year', date_labels = '%Y',
               expand = c(0, 0)) + 
  scale_y_continuous(expand = c(0,0)) +
  scale_fill_manual(values = c('grey'), labels = c('kkkk'))+
  scale_color_manual(values = c('black'), labels = c('llll')) +
  labs(x = NULL, y = NULL, fill = NULL, color = NULL) +
  guides(fill = guide_legend(order = 1), color = guide_legend(order = 2, override.aes = list(size = 2)))

plot