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

Skip to content

Enable set_{x|y|}label(loc={'left'|'right'|'center'}...) #15974

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
Jan 20, 2020
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/2019-12-20-set_xy_position
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Align labels to axes edges
--------------------------
`~.axes.Axes.set_xlabel`, `~.axes.Axes.set_ylabel` and `ColorbarBase.set_label`
support a parameter ``loc`` for simplified positioning. Supported values are
'left', 'center', 'right' The default is controlled via :rc:`xaxis.labelposition`
and :rc:`yaxis.labelposition`; the Colorbar label takes the rcParam based on its
orientation.
20 changes: 20 additions & 0 deletions examples/subplots_axes_and_figures/axis_labels_demo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
"""
===================
Axis Label Position
===================

Choose axis label position when calling `~.Axes.set_xlabel` and
`~.Axes.set_ylabel` as well as for colorbar.

"""
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

sc = ax.scatter([1, 2], [1, 2], c=[1, 2])
ax.set_ylabel('YLabel', loc='top')
ax.set_xlabel('XLabel', loc='left')
cbar = fig.colorbar(sc)
cbar.set_label("ZLabel", loc='top')

plt.show()
46 changes: 44 additions & 2 deletions lib/matplotlib/axes/_axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,8 @@ def get_xlabel(self):
label = self.xaxis.get_label()
return label.get_text()

def set_xlabel(self, xlabel, fontdict=None, labelpad=None, **kwargs):
def set_xlabel(self, xlabel, fontdict=None, labelpad=None, *,
loc=None, **kwargs):
"""
Set the label for the x-axis.

Expand All @@ -201,6 +202,10 @@ def set_xlabel(self, xlabel, fontdict=None, labelpad=None, **kwargs):
Spacing in points from the axes bounding box including ticks
and tick labels.

loc : {'left', 'center', 'right'}, default: :rc:`xaxis.labellocation`
The label position. This is a high-level alternative for passing
parameters *x* and *horizonatalalignment*.

Other Parameters
----------------
**kwargs : `.Text` properties
Expand All @@ -212,6 +217,22 @@ def set_xlabel(self, xlabel, fontdict=None, labelpad=None, **kwargs):
"""
if labelpad is not None:
self.xaxis.labelpad = labelpad
_protected_kw = ['x', 'horizontalalignment', 'ha']
if any([k in kwargs for k in _protected_kw]):
if loc is not None:
raise TypeError('Specifying *loc* is disallowed when any of '
'its corresponding low level kwargs {} '
'are supplied as well.'.format(_protected_kw))
loc = 'center'
else:
loc = loc if loc is not None else rcParams['xaxis.labellocation']
cbook._check_in_list(('left', 'center', 'right'), loc=loc)
if loc == 'right':
kwargs['x'] = 1.
kwargs['horizontalalignment'] = 'right'
elif loc == 'left':
kwargs['x'] = 0.
kwargs['horizontalalignment'] = 'left'
return self.xaxis.set_label_text(xlabel, fontdict, **kwargs)

def get_ylabel(self):
Expand All @@ -221,7 +242,8 @@ def get_ylabel(self):
label = self.yaxis.get_label()
return label.get_text()

def set_ylabel(self, ylabel, fontdict=None, labelpad=None, **kwargs):
def set_ylabel(self, ylabel, fontdict=None, labelpad=None, *,
loc=None, **kwargs):
"""
Set the label for the y-axis.

Expand All @@ -234,6 +256,10 @@ def set_ylabel(self, ylabel, fontdict=None, labelpad=None, **kwargs):
Spacing in points from the axes bounding box including ticks
and tick labels.

loc : {'bottom', 'center', 'top'}, default: :rc:`yaxis.labellocation`
The label position. This is a high-level alternative for passing
parameters *y* and *horizonatalalignment*.

Other Parameters
----------------
**kwargs : `.Text` properties
Expand All @@ -246,6 +272,22 @@ def set_ylabel(self, ylabel, fontdict=None, labelpad=None, **kwargs):
"""
if labelpad is not None:
self.yaxis.labelpad = labelpad
_protected_kw = ['y', 'horizontalalignment', 'ha']
if any([k in kwargs for k in _protected_kw]):
if loc is not None:
raise TypeError('Specifying *loc* is disallowed when any of '
'its corresponding low level kwargs {} '
'are supplied as well.'.format(_protected_kw))
loc = 'center'
else:
loc = loc if loc is not None else rcParams['yaxis.labellocation']
cbook._check_in_list(('bottom', 'center', 'top'), loc=loc)
if loc == 'top':
kwargs['y'] = 1.
kwargs['horizontalalignment'] = 'right'
elif loc == 'bottom':
kwargs['y'] = 0.
kwargs['horizontalalignment'] = 'left'
return self.yaxis.set_label_text(ylabel, fontdict, **kwargs)

def get_legend_handles_labels(self, legend_handler_map=None):
Expand Down
25 changes: 23 additions & 2 deletions lib/matplotlib/colorbar.py
Original file line number Diff line number Diff line change
Expand Up @@ -739,10 +739,31 @@ def _set_label(self):
self.ax.set_xlabel(self._label, **self._labelkw)
self.stale = True

def set_label(self, label, **kw):
def set_label(self, label, *, loc=None, **kwargs):
"""Add a label to the long axis of the colorbar."""
_pos_xy = 'y' if self.orientation == 'vertical' else 'x'
_protected_kw = [_pos_xy, 'horizontalalignment', 'ha']
if any([k in kwargs for k in _protected_kw]):
if loc is not None:
raise TypeError('Specifying *loc* is disallowed when any of '
'its corresponding low level kwargs {} '
'are supplied as well.'.format(_protected_kw))
loc = 'center'
else:
if loc is None:
loc = mpl.rcParams['%saxis.labellocation' % _pos_xy]
if self.orientation == 'vertical':
cbook._check_in_list(('bottom', 'center', 'top'), loc=loc)
else:
cbook._check_in_list(('left', 'center', 'right'), loc=loc)
if loc in ['right', 'top']:
kwargs[_pos_xy] = 1.
kwargs['horizontalalignment'] = 'right'
elif loc in ['left', 'bottom']:
kwargs[_pos_xy] = 0.
kwargs['horizontalalignment'] = 'left'
self._label = label
self._labelkw = kw
self._labelkw = kwargs
self._set_label()

def _outline(self, X, Y):
Expand Down
10 changes: 6 additions & 4 deletions lib/matplotlib/pyplot.py
Original file line number Diff line number Diff line change
Expand Up @@ -2855,16 +2855,18 @@ def title(label, fontdict=None, loc=None, pad=None, **kwargs):

# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.set_xlabel)
def xlabel(xlabel, fontdict=None, labelpad=None, **kwargs):
def xlabel(xlabel, fontdict=None, labelpad=None, *, loc=None, **kwargs):
return gca().set_xlabel(
xlabel, fontdict=fontdict, labelpad=labelpad, **kwargs)
xlabel, fontdict=fontdict, labelpad=labelpad, loc=loc,
**kwargs)


# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@docstring.copy(Axes.set_ylabel)
def ylabel(ylabel, fontdict=None, labelpad=None, **kwargs):
def ylabel(ylabel, fontdict=None, labelpad=None, *, loc=None, **kwargs):
return gca().set_ylabel(
ylabel, fontdict=fontdict, labelpad=labelpad, **kwargs)
ylabel, fontdict=fontdict, labelpad=labelpad, loc=loc,
**kwargs)


# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
Expand Down
12 changes: 11 additions & 1 deletion lib/matplotlib/rcsetup.py
Original file line number Diff line number Diff line change
Expand Up @@ -993,7 +993,13 @@ def validate_webagg_address(s):
raise ValueError("'webagg.address' is not a valid IP address")


validate_axes_titlelocation = ValidateInStrings('axes.titlelocation', ['left', 'center', 'right'])
validate_axes_titlelocation = ValidateInStrings('axes.titlelocation',
['left', 'center', 'right'])
_validate_xaxis_labellocation = ValidateInStrings('xaxis.labellocation',
['left', 'center', 'right'])
_validate_yaxis_labellocation = ValidateInStrings('yaxis.labellocation',
['bottom', 'center', 'top'])


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

# axis props
'xaxis.labellocation': ['center', _validate_xaxis_labellocation], # alignment of x axis title
'yaxis.labellocation': ['center', _validate_yaxis_labellocation], # alignment of y axis title

# axes props
'axes.axisbelow': ['line', validate_axisbelow],
'axes.facecolor': ['white', validate_color], # background color
Expand Down
53 changes: 53 additions & 0 deletions lib/matplotlib/tests/test_axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,59 @@ def test_get_labels():
assert ax.get_ylabel() == 'y label'


@check_figures_equal()
def test_label_loc_vertical(fig_test, fig_ref):
ax = fig_test.subplots()
sc = ax.scatter([1, 2], [1, 2], c=[1, 2])
ax.set_ylabel('Y Label', loc='top')
ax.set_xlabel('X Label', loc='right')
cbar = fig_test.colorbar(sc)
cbar.set_label("Z Label", loc='top')

ax = fig_ref.subplots()
sc = ax.scatter([1, 2], [1, 2], c=[1, 2])
ax.set_ylabel('Y Label', y=1, ha='right')
ax.set_xlabel('X Label', x=1, ha='right')
cbar = fig_ref.colorbar(sc)
cbar.set_label("Z Label", y=1, ha='right')


@check_figures_equal()
def test_label_loc_horizontal(fig_test, fig_ref):
ax = fig_test.subplots()
sc = ax.scatter([1, 2], [1, 2], c=[1, 2])
ax.set_ylabel('Y Label', loc='bottom')
ax.set_xlabel('X Label', loc='left')
cbar = fig_test.colorbar(sc, orientation='horizontal')
cbar.set_label("Z Label", loc='left')

ax = fig_ref.subplots()
sc = ax.scatter([1, 2], [1, 2], c=[1, 2])
ax.set_ylabel('Y Label', y=0, ha='left')
ax.set_xlabel('X Label', x=0, ha='left')
cbar = fig_ref.colorbar(sc, orientation='horizontal')
cbar.set_label("Z Label", x=0, ha='left')


@check_figures_equal()
def test_label_loc_rc(fig_test, fig_ref):
with matplotlib.rc_context({"xaxis.labellocation": "right",
"yaxis.labellocation": "top"}):
ax = fig_test.subplots()
sc = ax.scatter([1, 2], [1, 2], c=[1, 2])
ax.set_ylabel('Y Label')
ax.set_xlabel('X Label')
cbar = fig_test.colorbar(sc, orientation='horizontal')
cbar.set_label("Z Label")

ax = fig_ref.subplots()
sc = ax.scatter([1, 2], [1, 2], c=[1, 2])
ax.set_ylabel('Y Label', y=1, ha='right')
ax.set_xlabel('X Label', x=1, ha='right')
cbar = fig_ref.colorbar(sc, orientation='horizontal')
cbar.set_label("Z Label", x=1, ha='right')


@image_comparison(['acorr.png'], style='mpl20')
def test_acorr():
# Remove this line when this test image is regenerated.
Expand Down
6 changes: 6 additions & 0 deletions matplotlibrc.template
Original file line number Diff line number Diff line change
Expand Up @@ -415,6 +415,12 @@
#polaraxes.grid : True ## display grid on polar axes
#axes3d.grid : True ## display grid on 3d axes

## ***************************************************************************
## * AXIS *
## ***************************************************************************
#xaxis.labellocation : center ## alignment of the xaxis label: {left, right, center}
#yaxis.labellocation : center ## alignment of the yaxis label: {bottom, top, center}


## ***************************************************************************
## * DATES *
Expand Down