Last active
March 21, 2018 20:08
-
-
Save alexshpilkin/f91363b9854b8eed8aa4a384c1bd1baf to your computer and use it in GitHub Desktop.
Align vertical labels in subplots
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python | |
| import matplotlib.pyplot as plt | |
| import random | |
| import matplotlib.gridspec as gridspec | |
| random.seed(20) | |
| data1 = [random.random() for i in range(10)] | |
| data2 = [random.random()*1000 for i in range(10)] | |
| gs = gridspec.GridSpec(2,1) | |
| fig = plt.figure() | |
| ax1 = fig.add_subplot(gs[0]) | |
| ax1.plot(data1) | |
| ax1.set_ylabel(r'Label One', size =16) | |
| ax2 = fig.add_subplot(gs[1]) | |
| ax2.plot(data2) | |
| ax2.set_ylabel(r'Label Two', size =16) | |
| ### INTERESTING CODE BEGIN | |
| # FIXME This can be done cleaner by patching _update_label_positions once | |
| # matplotlib 2.1.3 is released | |
| def patch_axis(axis): | |
| def update(renderer): | |
| # Force recompute label positions | |
| ax1.yaxis._autolabelpos = ax2.yaxis._autolabelpos = True | |
| ax1.yaxis._get_tightbbox(renderer) | |
| ax2.yaxis._get_tightbbox(renderer) | |
| ax1.yaxis._autolabelpos = ax2.yaxis._autolabelpos = False | |
| # Update label positions | |
| (x1,y1) = ax1.yaxis.label.get_position() | |
| (x2,y2) = ax2.yaxis.label.get_position() | |
| ax1.yaxis.label.set_position((min(x1,x2), y1)) | |
| ax2.yaxis.label.set_position((min(x1,x2), y2)) | |
| old_draw = axis.draw | |
| def draw(renderer): | |
| update(renderer) | |
| return old_draw(renderer) | |
| axis.draw = draw | |
| old_get_tightbbox = axis._get_tightbbox = axis.get_tightbbox | |
| def get_tightbbox(renderer): | |
| update(renderer) | |
| return old_get_tightbbox(renderer) | |
| axis.get_tightbbox = get_tightbbox | |
| patch_axis(ax1.yaxis) | |
| patch_axis(ax2.yaxis) | |
| ### INTERESTING CODE END | |
| plt.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment