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!
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-boxto one of the following values:guide-box-right,guide-box-left,guide-box-bottom,guide-box-top, orguide-box-inside.Example: