rggplot2cowplot

R. get_legend() from cowplot package no longer work for ggplot2 version 3.5.0


get_legend() now returns error for ggplot object

I used to do get_legend(plot) to extract the legend part of the plot. It still works for ggplot2 version 3.4.4. Now that I updated my ggplot2 to version 3.5.0. I think it changes the way legend is stored. Now get_legend(plot) will return nothing and give the warning:

get_legend(plot)

Warning messages:
1: In get_plot_component(plot, "guide-box") :
  Multiple components found; returning the first one. To return all, use `return_all = TRUE`.

I have also tried get_plot_component(). It doesn't work, nor does list(get_plot_component()) work.

legend = get_plot_component(plot, 'guide-box', return_all = TRUE)
ggdraw(legend)

Warning messages:
1: In as_grob.default(plot) :
  Cannot convert object of class list into a grob.

Is there any other ways to extract the legend of the plot? Thank you!


Solution

  • As a temporary solution, change your second argument to get_plot_component().

    You have legend = get_plot_component(plot, 'guide-box', return_all = TRUE).

    Change the value guide-box to one of the following values: guide-box-right, guide-box-left, guide-box-bottom, guide-box-top, or guide-box-inside.

    Example:

    df <- data.frame(pet = c("cat","dog","snake"),
      count = c(20,5,94))
    
    plot <- ggplot2::ggplot(df, ggplot2::aes(pet, count, fill = pet)) +
      ggplot2::geom_col() +
      ggplot2::theme(legend.position = "top") # <- specify position of legend
    
    legend = cowplot::get_plot_component(plot, 'guide-box-top', return_all = TRUE)
    cowplot::ggdraw(legend)