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

Example current plot:

I could not find an answer here yet, at least not one that worked for me.
I am attempting to place the title of a horizontally placed legend on top of the code.
However, when using the legend. Title = ‘top’ nothing changes, and he stays positioned to the left.

Am I missing something since I cannot imagine it is impossible to position a legend title?

>Solution :

Use guide_legend:

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

For the title to be centered, you can add title.hjust = 0.5 in the guide_legend function.

enter image description here

Leave a Reply