Thanks to visit codestin.com
Credit goes to github.com

Skip to content

ENH: add pad kwarg to set_title #9816

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 20, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions doc/users/next_whats_new/2017_11_19_title_pad.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Add *pad* kwarg to ax.set_title
-------------------------------

The method `axes.set_title` now has a *pad* kwarg, that specifies the
distance from the top of an axes to where the title is drawn. The units
of *pad* is points, and the default is the value of the (already-existing)
``rcParams['axes.titlepad']``.
12 changes: 11 additions & 1 deletion lib/matplotlib/axes/_axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

import functools
import itertools
import logging
import math
import warnings

Expand Down Expand Up @@ -42,6 +43,7 @@
from matplotlib.container import BarContainer, ErrorbarContainer, StemContainer
from matplotlib.axes._base import _AxesBase, _process_plot_format

_log = logging.getLogger(__name__)

rcParams = matplotlib.rcParams

Expand Down Expand Up @@ -134,7 +136,8 @@ def get_title(self, loc="center"):
raise ValueError("'%s' is not a valid location" % loc)
return title.get_text()

def set_title(self, label, fontdict=None, loc="center", **kwargs):
def set_title(self, label, fontdict=None, loc="center", pad=None,
**kwargs):
"""
Set a title for the axes.

Expand All @@ -159,6 +162,10 @@ def set_title(self, label, fontdict=None, loc="center", **kwargs):
loc : {'center', 'left', 'right'}, str, optional
Which title to set, defaults to 'center'

pad : float
The offset of the title from the top of the axes, in points.
Default is ``None`` to use rcParams['axes.titlepad'].

Returns
-------
text : :class:`~matplotlib.text.Text`
Expand All @@ -182,6 +189,9 @@ def set_title(self, label, fontdict=None, loc="center", **kwargs):
'fontweight': rcParams['axes.titleweight'],
'verticalalignment': 'baseline',
'horizontalalignment': loc.lower()}
if pad is None:
pad = rcParams['axes.titlepad']
self._set_title_offset_trans(float(pad))
title.set_text(label)
title.update(default)
if fontdict is not None:
Expand Down
22 changes: 16 additions & 6 deletions lib/matplotlib/axes/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -1053,10 +1053,6 @@ def cla(self):
size=rcParams['axes.titlesize'],
weight=rcParams['axes.titleweight'])

title_offset_points = rcParams['axes.titlepad']
self.titleOffsetTrans = mtransforms.ScaledTranslation(
0.0, title_offset_points / 72.0,
self.figure.dpi_scale_trans)
self.title = mtext.Text(
x=0.5, y=1.0, text='',
fontproperties=props,
Expand All @@ -1074,10 +1070,12 @@ def cla(self):
verticalalignment='baseline',
horizontalalignment='right',
)
title_offset_points = rcParams['axes.titlepad']
# refactor this out so it can be called in ax.set_title if
# pad argument used...
self._set_title_offset_trans(title_offset_points)

for _title in (self.title, self._left_title, self._right_title):
_title.set_transform(self.transAxes + self.titleOffsetTrans)
_title.set_clip_box(None)
self._set_artist_props(_title)

# The patch draws the background of the axes. We want this to be below
Expand Down Expand Up @@ -1134,6 +1132,18 @@ def set_facecolor(self, color):
return self.patch.set_facecolor(color)
set_fc = set_facecolor

def _set_title_offset_trans(self, title_offset_points):
"""
Set the offset for the title either from rcParams['axes.titlepad']
or from set_title kwarg ``pad``.
"""
self.titleOffsetTrans = mtransforms.ScaledTranslation(
0.0, title_offset_points / 72.0,
self.figure.dpi_scale_trans)
for _title in (self.title, self._left_title, self._right_title):
_title.set_transform(self.transAxes + self.titleOffsetTrans)
_title.set_clip_box(None)

def set_prop_cycle(self, *args, **kwargs):
"""
Set the property cycle for any future plot commands on this Axes.
Expand Down
16 changes: 16 additions & 0 deletions lib/matplotlib/tests/test_axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -4917,6 +4917,22 @@ def test_dash_offset():
ax.plot(x, j*y, ls=(j, (10, 10)), lw=5, color='k')


def test_title_pad():
# check that title padding puts the title in the right
# place...
fig, ax = plt.subplots()
ax.set_title('aardvark', pad=30.)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍 for use of 'aardvark'!

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wish I could claim credit, but I just cut and pasted from elsewhere. I hope its a good inside joke...

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well at least it is likely to be the first word in English-dictionaries, isn't it ^^? It may actually be(come) a running gag in Matploltib code too: I used it as well in some tests with strings, copy-pasting it from some other existing code section as @jklymak did... (I did not even understand it was a proper word at that time 🐑 )

m = ax.titleOffsetTrans.get_matrix()
assert m[1, -1] == (30. / 72. * fig.dpi)
ax.set_title('aardvark', pad=0.)
m = ax.titleOffsetTrans.get_matrix()
assert m[1, -1] == 0.
# check that it is reverted...
ax.set_title('aardvark', pad=None)
m = ax.titleOffsetTrans.get_matrix()
assert m[1, -1] == (matplotlib.rcParams['axes.titlepad'] / 72. * fig.dpi)


def test_title_location_roundtrip():
fig, ax = plt.subplots()
ax.set_title('aardvark')
Expand Down