diff --git a/doc/users/next_whats_new/legend_title_fontsize_kwarg.rst b/doc/users/next_whats_new/legend_title_fontsize_kwarg.rst new file mode 100644 index 000000000000..6544e42afb9a --- /dev/null +++ b/doc/users/next_whats_new/legend_title_fontsize_kwarg.rst @@ -0,0 +1,8 @@ +Legend now has a title_fontsize kwarg +------------------------------------- + +The title for a `.Figure.legend` and `.Axes.legend` can now have its +fontsize set via the ``title_fontsize`` kwarg, defaults to ``None``, which +means the legend title will have the same fontsize as the axes default +fontsize (*not* the legend fontsize, set by the ``fontsize`` kwarg or +:rc:`legend.fontsize`). diff --git a/lib/matplotlib/legend.py b/lib/matplotlib/legend.py index 585915e0c554..08b01f82b40d 100644 --- a/lib/matplotlib/legend.py +++ b/lib/matplotlib/legend.py @@ -232,6 +232,9 @@ def _update_bbox_to_anchor(self, loc_in_canvas): title : str or None The legend's title. Default is no title (``None``). +title_fontsize: str or None + The fontsize of the legend's title. Default is the default fontsize. + borderpad : float or None The fractional whitespace inside the legend border. Measured in font-size units. @@ -333,7 +336,7 @@ def __init__(self, parent, handles, labels, # box, none use rc shadow=None, title=None, # set a title for the legend - + title_fontsize=None, # set to ax.fontsize if None framealpha=None, # set frame alpha edgecolor=None, # frame patch edgecolor facecolor=None, # frame patch facecolor @@ -539,7 +542,12 @@ def __init__(self, parent, handles, labels, self.get_frame().set_alpha(framealpha) self._loc = loc - self.set_title(title) + # figure out title fontsize: + if title_fontsize is not None: + tprop = FontProperties(size=title_fontsize) + else: + tprop = None + self.set_title(title, prop=tprop) self._last_fontsize_points = self._fontsize self._draggable = None diff --git a/lib/matplotlib/tests/test_legend.py b/lib/matplotlib/tests/test_legend.py index b1d176ec8a0f..6e377505a078 100644 --- a/lib/matplotlib/tests/test_legend.py +++ b/lib/matplotlib/tests/test_legend.py @@ -502,3 +502,11 @@ def test_legend_proper_window_extent(): leg = ax.legend() x02 = leg.get_window_extent(fig.canvas.get_renderer()).x0 assert pytest.approx(x01*2, 0.1) == x02 + + +def test_legend_title_fontsize(): + # test the title_fontsize kwarg + fig, ax = plt.subplots() + ax.plot(range(10)) + leg = ax.legend(title='Aardvark', title_fontsize=22) + assert leg.get_title().get_fontsize() == 22