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

Skip to content

Commit b72fd23

Browse files
committed
added support for custom positioning of axis labels
svn path=/trunk/matplotlib/; revision=5597
1 parent 4264bc7 commit b72fd23

3 files changed

Lines changed: 86 additions & 6 deletions

File tree

doc/faq/howto_faq.rst

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,24 @@ are ``markerfacecolor``, ``markeredgecolor``, ``markeredgewidth``,
113113
``markersize``. For more information on configuring ticks, see
114114
:ref:`axis-container` and :ref:`tick-container`.
115115

116+
117+
.. _howto-align-label:
118+
119+
How do I align my ylabels across multiple subplots?
120+
===================================================
121+
122+
If you have multiple subplots over one another, and the y data have
123+
different scales, you can often get ylabels that do not align
124+
vertically across the multiple subplots, which can be unattractive.
125+
By default, matplotlib positions the x location of the ylabel so that
126+
it does not overlap any of the y ticks. You can override this default
127+
behavior by specifying the coordinates of the label. The example
128+
below shows the default behavior in the left subplots, and the manual
129+
setting in the right subplots.
130+
131+
.. plot:: align_ylabels.py
132+
:include-source:
133+
116134
.. _howto-webapp:
117135

118136
How do I use matplotlib in a web application server?

doc/pyplots/align_ylabels.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import numpy as np
2+
import matplotlib.pyplot as plt
3+
4+
box = dict(facecolor='yellow', pad=5, alpha=0.2)
5+
6+
fig = plt.figure()
7+
fig.subplots_adjust(left=0.2, wspace=0.6)
8+
9+
10+
ax1 = fig.add_subplot(221)
11+
ax1.plot(2000*np.random.rand(10))
12+
ax1.set_title('ylabels not aligned')
13+
ax1.set_ylabel('misaligned 1', bbox=box)
14+
ax1.set_ylim(0, 2000)
15+
ax3 = fig.add_subplot(223)
16+
ax3.set_ylabel('misaligned 2',bbox=box)
17+
ax3.plot(np.random.rand(10))
18+
19+
20+
labelx = -0.3 # axes coords
21+
22+
ax2 = fig.add_subplot(222)
23+
ax2.set_title('ylabels aligned')
24+
ax2.plot(2000*np.random.rand(10))
25+
ax2.set_ylabel('aligned 1', bbox=box)
26+
ax2.yaxis.set_label_coords(labelx, 0.5)
27+
ax2.set_ylim(0, 2000)
28+
29+
ax4 = fig.add_subplot(224)
30+
ax4.plot(np.random.rand(10))
31+
ax4.set_ylabel('aligned 2', bbox=box)
32+
ax4.yaxis.set_label_coords(labelx, 0.5)
33+
34+
35+
plt.show()

lib/matplotlib/axis.py

Lines changed: 33 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -503,9 +503,9 @@ class Axis(artist.Artist):
503503

504504
"""
505505
Public attributes
506-
transData - transform data coords to display coords
507-
transAxis - transform axis coords to display coords
508506
507+
* transData - transform data coords to display coords
508+
* transAxis - transform axis coords to display coords
509509
510510
"""
511511
LABELPAD = 5
@@ -533,6 +533,7 @@ def __init__(self, axes, pickradius=15):
533533
#self.major = dummy()
534534
#self.minor = dummy()
535535

536+
self._autolabelpos = True
536537
self.label = self._get_label()
537538
self.offsetText = self._get_offset_text()
538539
self.majorTicks = []
@@ -542,6 +543,29 @@ def __init__(self, axes, pickradius=15):
542543
self.cla()
543544
self.set_scale('linear')
544545

546+
547+
def set_label_coords(self, x, y, transform=None):
548+
"""
549+
Set the coordinates of the label. By default, the x
550+
coordinate of the y label is determined by the tick label
551+
bounding boxes, but this can lead to poor alignment of
552+
multiple ylabels if there are multiple axes. Ditto for the y
553+
coodinate of the x label.
554+
555+
You can also specify the coordinate system of the label with
556+
the transform. If None, the default coordinate system will be
557+
the axes coordinate system (0,0) is (left,bottom), (0.5, 0.5)
558+
is middle, etc
559+
560+
"""
561+
562+
self._autolabelpos = False
563+
if transform is None:
564+
transform = self.axes.transAxes
565+
566+
self.label.set_transform(transform)
567+
self.label.set_position((x, y))
568+
545569
def get_transform(self):
546570
return self._scale.get_transform()
547571

@@ -703,7 +727,9 @@ def draw(self, renderer, *args, **kwargs):
703727
# just the tick labels that actually overlap note we need a
704728
# *copy* of the axis label box because we don't wan't to scale
705729
# the actual bbox
730+
706731
self._update_label_position(ticklabelBoxes, ticklabelBoxes2)
732+
707733
self.label.draw(renderer)
708734

709735
self._update_offset_text_position(ticklabelBoxes, ticklabelBoxes2)
@@ -1139,8 +1165,9 @@ def _get_label(self):
11391165
verticalalignment='top',
11401166
horizontalalignment='center',
11411167
)
1168+
11421169
label.set_transform( mtransforms.blended_transform_factory(
1143-
self.axes.transAxes, mtransforms.IdentityTransform() ))
1170+
self.axes.transAxes, mtransforms.IdentityTransform() ))
11441171

11451172
self._set_artist_props(label)
11461173
self.label_position='bottom'
@@ -1184,7 +1211,7 @@ def _update_label_position(self, bboxes, bboxes2):
11841211
Update the label position based on the sequence of bounding
11851212
boxes of all the ticklabels
11861213
"""
1187-
1214+
if not self._autolabelpos: return
11881215
x,y = self.label.get_position()
11891216
if self.label_position == 'bottom':
11901217
if not len(bboxes):
@@ -1374,7 +1401,7 @@ def _get_label(self):
13741401
rotation='vertical',
13751402
)
13761403
label.set_transform( mtransforms.blended_transform_factory(
1377-
mtransforms.IdentityTransform(), self.axes.transAxes) )
1404+
mtransforms.IdentityTransform(), self.axes.transAxes) )
13781405

13791406
self._set_artist_props(label)
13801407
self.label_position='left'
@@ -1418,7 +1445,7 @@ def _update_label_position(self, bboxes, bboxes2):
14181445
Update the label position based on the sequence of bounding
14191446
boxes of all the ticklabels
14201447
"""
1421-
1448+
if not self._autolabelpos: return
14221449
x,y = self.label.get_position()
14231450
if self.label_position == 'left':
14241451
if not len(bboxes):

0 commit comments

Comments
 (0)