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

Skip to content

Commit cc55b47

Browse files
authored
Enable set_{x|y|}label(loc={'left'|'right'|'center'}...) (#15974)
Enable set_{x|y|}label(loc={'left'|'right'|'center'}...)
2 parents 20805b8 + 6ad9906 commit cc55b47

File tree

8 files changed

+170
-9
lines changed

8 files changed

+170
-9
lines changed
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
Align labels to axes edges
2+
--------------------------
3+
`~.axes.Axes.set_xlabel`, `~.axes.Axes.set_ylabel` and `ColorbarBase.set_label`
4+
support a parameter ``loc`` for simplified positioning. Supported values are
5+
'left', 'center', 'right' The default is controlled via :rc:`xaxis.labelposition`
6+
and :rc:`yaxis.labelposition`; the Colorbar label takes the rcParam based on its
7+
orientation.
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
"""
2+
===================
3+
Axis Label Position
4+
===================
5+
6+
Choose axis label position when calling `~.Axes.set_xlabel` and
7+
`~.Axes.set_ylabel` as well as for colorbar.
8+
9+
"""
10+
import matplotlib.pyplot as plt
11+
12+
fig, ax = plt.subplots()
13+
14+
sc = ax.scatter([1, 2], [1, 2], c=[1, 2])
15+
ax.set_ylabel('YLabel', loc='top')
16+
ax.set_xlabel('XLabel', loc='left')
17+
cbar = fig.colorbar(sc)
18+
cbar.set_label("ZLabel", loc='top')
19+
20+
plt.show()

lib/matplotlib/axes/_axes.py

Lines changed: 44 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -188,7 +188,8 @@ def get_xlabel(self):
188188
label = self.xaxis.get_label()
189189
return label.get_text()
190190

191-
def set_xlabel(self, xlabel, fontdict=None, labelpad=None, **kwargs):
191+
def set_xlabel(self, xlabel, fontdict=None, labelpad=None, *,
192+
loc=None, **kwargs):
192193
"""
193194
Set the label for the x-axis.
194195
@@ -201,6 +202,10 @@ def set_xlabel(self, xlabel, fontdict=None, labelpad=None, **kwargs):
201202
Spacing in points from the axes bounding box including ticks
202203
and tick labels.
203204
205+
loc : {'left', 'center', 'right'}, default: :rc:`xaxis.labellocation`
206+
The label position. This is a high-level alternative for passing
207+
parameters *x* and *horizonatalalignment*.
208+
204209
Other Parameters
205210
----------------
206211
**kwargs : `.Text` properties
@@ -212,6 +217,22 @@ def set_xlabel(self, xlabel, fontdict=None, labelpad=None, **kwargs):
212217
"""
213218
if labelpad is not None:
214219
self.xaxis.labelpad = labelpad
220+
_protected_kw = ['x', 'horizontalalignment', 'ha']
221+
if any([k in kwargs for k in _protected_kw]):
222+
if loc is not None:
223+
raise TypeError('Specifying *loc* is disallowed when any of '
224+
'its corresponding low level kwargs {} '
225+
'are supplied as well.'.format(_protected_kw))
226+
loc = 'center'
227+
else:
228+
loc = loc if loc is not None else rcParams['xaxis.labellocation']
229+
cbook._check_in_list(('left', 'center', 'right'), loc=loc)
230+
if loc == 'right':
231+
kwargs['x'] = 1.
232+
kwargs['horizontalalignment'] = 'right'
233+
elif loc == 'left':
234+
kwargs['x'] = 0.
235+
kwargs['horizontalalignment'] = 'left'
215236
return self.xaxis.set_label_text(xlabel, fontdict, **kwargs)
216237

217238
def get_ylabel(self):
@@ -221,7 +242,8 @@ def get_ylabel(self):
221242
label = self.yaxis.get_label()
222243
return label.get_text()
223244

224-
def set_ylabel(self, ylabel, fontdict=None, labelpad=None, **kwargs):
245+
def set_ylabel(self, ylabel, fontdict=None, labelpad=None, *,
246+
loc=None, **kwargs):
225247
"""
226248
Set the label for the y-axis.
227249
@@ -234,6 +256,10 @@ def set_ylabel(self, ylabel, fontdict=None, labelpad=None, **kwargs):
234256
Spacing in points from the axes bounding box including ticks
235257
and tick labels.
236258
259+
loc : {'bottom', 'center', 'top'}, default: :rc:`yaxis.labellocation`
260+
The label position. This is a high-level alternative for passing
261+
parameters *y* and *horizonatalalignment*.
262+
237263
Other Parameters
238264
----------------
239265
**kwargs : `.Text` properties
@@ -246,6 +272,22 @@ def set_ylabel(self, ylabel, fontdict=None, labelpad=None, **kwargs):
246272
"""
247273
if labelpad is not None:
248274
self.yaxis.labelpad = labelpad
275+
_protected_kw = ['y', 'horizontalalignment', 'ha']
276+
if any([k in kwargs for k in _protected_kw]):
277+
if loc is not None:
278+
raise TypeError('Specifying *loc* is disallowed when any of '
279+
'its corresponding low level kwargs {} '
280+
'are supplied as well.'.format(_protected_kw))
281+
loc = 'center'
282+
else:
283+
loc = loc if loc is not None else rcParams['yaxis.labellocation']
284+
cbook._check_in_list(('bottom', 'center', 'top'), loc=loc)
285+
if loc == 'top':
286+
kwargs['y'] = 1.
287+
kwargs['horizontalalignment'] = 'right'
288+
elif loc == 'bottom':
289+
kwargs['y'] = 0.
290+
kwargs['horizontalalignment'] = 'left'
249291
return self.yaxis.set_label_text(ylabel, fontdict, **kwargs)
250292

251293
def get_legend_handles_labels(self, legend_handler_map=None):

lib/matplotlib/colorbar.py

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -739,10 +739,31 @@ def _set_label(self):
739739
self.ax.set_xlabel(self._label, **self._labelkw)
740740
self.stale = True
741741

742-
def set_label(self, label, **kw):
742+
def set_label(self, label, *, loc=None, **kwargs):
743743
"""Add a label to the long axis of the colorbar."""
744+
_pos_xy = 'y' if self.orientation == 'vertical' else 'x'
745+
_protected_kw = [_pos_xy, 'horizontalalignment', 'ha']
746+
if any([k in kwargs for k in _protected_kw]):
747+
if loc is not None:
748+
raise TypeError('Specifying *loc* is disallowed when any of '
749+
'its corresponding low level kwargs {} '
750+
'are supplied as well.'.format(_protected_kw))
751+
loc = 'center'
752+
else:
753+
if loc is None:
754+
loc = mpl.rcParams['%saxis.labellocation' % _pos_xy]
755+
if self.orientation == 'vertical':
756+
cbook._check_in_list(('bottom', 'center', 'top'), loc=loc)
757+
else:
758+
cbook._check_in_list(('left', 'center', 'right'), loc=loc)
759+
if loc in ['right', 'top']:
760+
kwargs[_pos_xy] = 1.
761+
kwargs['horizontalalignment'] = 'right'
762+
elif loc in ['left', 'bottom']:
763+
kwargs[_pos_xy] = 0.
764+
kwargs['horizontalalignment'] = 'left'
744765
self._label = label
745-
self._labelkw = kw
766+
self._labelkw = kwargs
746767
self._set_label()
747768

748769
def _outline(self, X, Y):

lib/matplotlib/pyplot.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2855,16 +2855,18 @@ def title(label, fontdict=None, loc=None, pad=None, **kwargs):
28552855

28562856
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
28572857
@docstring.copy(Axes.set_xlabel)
2858-
def xlabel(xlabel, fontdict=None, labelpad=None, **kwargs):
2858+
def xlabel(xlabel, fontdict=None, labelpad=None, *, loc=None, **kwargs):
28592859
return gca().set_xlabel(
2860-
xlabel, fontdict=fontdict, labelpad=labelpad, **kwargs)
2860+
xlabel, fontdict=fontdict, labelpad=labelpad, loc=loc,
2861+
**kwargs)
28612862

28622863

28632864
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
28642865
@docstring.copy(Axes.set_ylabel)
2865-
def ylabel(ylabel, fontdict=None, labelpad=None, **kwargs):
2866+
def ylabel(ylabel, fontdict=None, labelpad=None, *, loc=None, **kwargs):
28662867
return gca().set_ylabel(
2867-
ylabel, fontdict=fontdict, labelpad=labelpad, **kwargs)
2868+
ylabel, fontdict=fontdict, labelpad=labelpad, loc=loc,
2869+
**kwargs)
28682870

28692871

28702872
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.

lib/matplotlib/rcsetup.py

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -993,7 +993,13 @@ def validate_webagg_address(s):
993993
raise ValueError("'webagg.address' is not a valid IP address")
994994

995995

996-
validate_axes_titlelocation = ValidateInStrings('axes.titlelocation', ['left', 'center', 'right'])
996+
validate_axes_titlelocation = ValidateInStrings('axes.titlelocation',
997+
['left', 'center', 'right'])
998+
_validate_xaxis_labellocation = ValidateInStrings('xaxis.labellocation',
999+
['left', 'center', 'right'])
1000+
_validate_yaxis_labellocation = ValidateInStrings('yaxis.labellocation',
1001+
['bottom', 'center', 'top'])
1002+
9971003

9981004
# a map from key -> value, converter
9991005
defaultParams = {
@@ -1159,6 +1165,10 @@ def validate_webagg_address(s):
11591165
# errorbar props
11601166
'errorbar.capsize': [0, validate_float],
11611167

1168+
# axis props
1169+
'xaxis.labellocation': ['center', _validate_xaxis_labellocation], # alignment of x axis title
1170+
'yaxis.labellocation': ['center', _validate_yaxis_labellocation], # alignment of y axis title
1171+
11621172
# axes props
11631173
'axes.axisbelow': ['line', validate_axisbelow],
11641174
'axes.facecolor': ['white', validate_color], # background color

lib/matplotlib/tests/test_axes.py

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,59 @@ def test_get_labels():
4242
assert ax.get_ylabel() == 'y label'
4343

4444

45+
@check_figures_equal()
46+
def test_label_loc_vertical(fig_test, fig_ref):
47+
ax = fig_test.subplots()
48+
sc = ax.scatter([1, 2], [1, 2], c=[1, 2])
49+
ax.set_ylabel('Y Label', loc='top')
50+
ax.set_xlabel('X Label', loc='right')
51+
cbar = fig_test.colorbar(sc)
52+
cbar.set_label("Z Label", loc='top')
53+
54+
ax = fig_ref.subplots()
55+
sc = ax.scatter([1, 2], [1, 2], c=[1, 2])
56+
ax.set_ylabel('Y Label', y=1, ha='right')
57+
ax.set_xlabel('X Label', x=1, ha='right')
58+
cbar = fig_ref.colorbar(sc)
59+
cbar.set_label("Z Label", y=1, ha='right')
60+
61+
62+
@check_figures_equal()
63+
def test_label_loc_horizontal(fig_test, fig_ref):
64+
ax = fig_test.subplots()
65+
sc = ax.scatter([1, 2], [1, 2], c=[1, 2])
66+
ax.set_ylabel('Y Label', loc='bottom')
67+
ax.set_xlabel('X Label', loc='left')
68+
cbar = fig_test.colorbar(sc, orientation='horizontal')
69+
cbar.set_label("Z Label", loc='left')
70+
71+
ax = fig_ref.subplots()
72+
sc = ax.scatter([1, 2], [1, 2], c=[1, 2])
73+
ax.set_ylabel('Y Label', y=0, ha='left')
74+
ax.set_xlabel('X Label', x=0, ha='left')
75+
cbar = fig_ref.colorbar(sc, orientation='horizontal')
76+
cbar.set_label("Z Label", x=0, ha='left')
77+
78+
79+
@check_figures_equal()
80+
def test_label_loc_rc(fig_test, fig_ref):
81+
with matplotlib.rc_context({"xaxis.labellocation": "right",
82+
"yaxis.labellocation": "top"}):
83+
ax = fig_test.subplots()
84+
sc = ax.scatter([1, 2], [1, 2], c=[1, 2])
85+
ax.set_ylabel('Y Label')
86+
ax.set_xlabel('X Label')
87+
cbar = fig_test.colorbar(sc, orientation='horizontal')
88+
cbar.set_label("Z Label")
89+
90+
ax = fig_ref.subplots()
91+
sc = ax.scatter([1, 2], [1, 2], c=[1, 2])
92+
ax.set_ylabel('Y Label', y=1, ha='right')
93+
ax.set_xlabel('X Label', x=1, ha='right')
94+
cbar = fig_ref.colorbar(sc, orientation='horizontal')
95+
cbar.set_label("Z Label", x=1, ha='right')
96+
97+
4598
@image_comparison(['acorr.png'], style='mpl20')
4699
def test_acorr():
47100
# Remove this line when this test image is regenerated.

matplotlibrc.template

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -415,6 +415,12 @@
415415
#polaraxes.grid : True ## display grid on polar axes
416416
#axes3d.grid : True ## display grid on 3d axes
417417

418+
## ***************************************************************************
419+
## * AXIS *
420+
## ***************************************************************************
421+
#xaxis.labellocation : center ## alignment of the xaxis label: {left, right, center}
422+
#yaxis.labellocation : center ## alignment of the yaxis label: {bottom, top, center}
423+
418424

419425
## ***************************************************************************
420426
## * DATES *

0 commit comments

Comments
 (0)