如何在水平图例上方绘制图例标题

How to plot the legend title above a horizontal legend

# Create the dataset
Groups <- c('Treatment A','Treatment A','Treatment A','Treatment A',
           'Treatment B', 'Treatment B', 'Treatment B','Treatment B',
           'Treatment C', 'Treatment C', 'Treatment C', 'Treatment C')
Val <- c(2, 5, 3, 7,
         4, 3, 6, 2,
         7, 4, 3.5, 4)
Timepoint <- c(1, 2, 3, 4,
               1, 2, 3, 4,
               1, 2, 3, 4)

df2 <- data.frame(Groups, Val, Timepoint)

data_label_1 <- df2
data_label_1$label[which(data_label_1$Timepoint == max(data_label_1$Timepoint))] <-
  data_label_1$Group[which(data_label_1$Timepoint == max(data_label_1$Timepoint))]

g4 <- ggplot(data_label_1, aes(x = Timepoint, y = Val, groups = Groups)) +
  geom_line(size = 0.8, aes(linetype=Groups)) +
  ylab('Value') +
  theme(panel.background = element_rect(fill = "white",
                                colour = "white",
                                size = 0.5, linetype = "solid"),
        panel.grid.major = element_line(size = 0.5, linetype = 'solid',
                                colour = "#e7e3d8"),
        panel.grid.minor = element_line(size = 0.25,
                                        linetype = 'solid',
                                        colour = "#e7e3d8"),
        legend.background = element_rect(fill = "white", color = "black"),
        legend.key = element_rect(fill = "white"),
        legend.position = c(0.5, 0.9),
        legend.direction = 'horizontal',
        legend.box = 'horizontal'
        )
g4

当前情节示例:

我在这里找不到答案,至少没有适合我的答案。 我试图将水平放置的图例的标题放在代码的顶部。 但是,在使用图例时。 Title = 'top' 没有任何变化,他仍然位于左侧。

我是否遗漏了什么,因为我无法想象无法定位图例标题?

使用guide_legend:

g4 +
 guides(linetype = guide_legend(title.position = "top"))

要让标题居中,可以在guide_legend函数中加入title.hjust = 0.5