change legend title

Hi,
I am combining multiple plots using "cowplot". I want to build one legend. Here is a sample code:

plot_t = function(df,colors){
    p = ggplot(df,aes(s,tr,col=strategy),size=1)+
      geom_line(size=1)+
      scale_x_continuous(breaks = scales::pretty_breaks(n = 5)) +
      scale_y_continuous(breaks = scales::pretty_breaks(n = 10)) +
      labs(x='x',y='y')+
      theme(legend.position = "none",
            legend.title = element_text(size=18),
            legend.text = element_text(size=18),
            axis.title = element_text(size=18),
            axis.text = element_text(size=16,color="black"),
            #axis.text.x = element_text(angle = 90),
            panel.grid.major.x = element_blank(),
            panel.grid.minor.x = element_blank(),
            panel.grid.major.y = element_line(colour = "gray50", linetype="dashed"),
            
            panel.background = element_blank(), 
            axis.line = element_line(colour = "black")
      )+
      scale_fill_manual(values = colors)+
      scale_color_manual(values = colors)
    return(p)
  }
 rplots <- plot_grid(
    plot_t,ploy_i,ploy_c,
    align = 'vh',
    labels = "AUTO",
    hjust = -1,
    nrow = 1
  )
 
  legend_b = get_legend(
    plot_t + 
      guides(color = guide_legend(nrow = 1))+
      theme(legend.position = "bottom"))
 plots = plot_grid(rplots, legend_b, ncol = 1, rel_heights = c(1, .1))

It worked, but I just want to set the legend title manually. I tried to add the title in labs. Two legends were created. I would appreciate any suggestion.

Thanks

It may be useful if you provide what "t", "i" and "c" look like. Though have you thought about using patchwork over cowplot? It's a more modern, simple way of achieving plot alignment:

library(tidyverse)
library(patchwork)

plt = ggplot(mtcars, aes(mpg, disp, color = cyl)) +
  geom_point()

# default patchwork

plt + plt + plt

# tag & collect legends, put legend at bottom

plt + plt + plt +
  plot_annotation(tag_levels = "A") +
  plot_layout(nrow = 1, guides = "collect") &
  theme(legend.position = "bottom")

Created on 2022-02-11 by the reprex package (v2.0.1)

1 Like

Thanks, I checked Patchwork, still can not figure out, how to set the title for the legend manually.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.