Created
March 9, 2012 03:31
-
-
Save pmarshwx/2004869 to your computer and use it in GitHub Desktop.
Centered Text Issue
This file contains 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 as mpl | |
import matplotlib.pyplot as plt | |
from mpl_toolkits.axes_grid1 import axes_divider as divider | |
from mpl_toolkits.axes_grid1.anchored_artists import AnchoredText | |
def add_center_text(ax): | |
pos = ax.get_position().bounds | |
l, b, w, h = pos | |
w2 = 0.5 | |
l2 = l + 0.5*w - w2/2. | |
b2 = b+0.8575*h | |
h2 = 0.1*h | |
ax2 = plt.axes([l2, b2, w2, h2], xticks=[], yticks=[], frameon=False) | |
ax2.text(0.5, 0.5, "Centered Title", ha='center', va='center', fontsize=18, | |
bbox=dict(boxstyle='round, pad=0.5, rounding_size=0.25', fc="white", | |
ec="k", lw=2)) | |
plt.axes(ax) | |
def add_center_text_alt(locator, ax): | |
pos = locator.get_position_runtime(ax, mpl.get_backend()) | |
l, b, w, h = pos | |
w2 = 0.5 | |
l2 = l + 0.5*w - w2/2. | |
b2 = b+0.8575*h | |
h2 = 0.1*h | |
ax2 = plt.axes([l2, b2, w2, h2], xticks=[], yticks=[], frameon=False) | |
ax2.text(0.5, 0.5, "Centered Title", ha='center', va='center', fontsize=18, | |
bbox=dict(boxstyle='round, pad=0.5, rounding_size=0.25', fc="white", | |
ec="k", lw=2)) | |
plt.axes(ax) | |
def add_center_text_alt2(ax, fsize=10): | |
title = 'Hello World\nToday' | |
at = AnchoredText(title, prop=dict(size=fsize, ha='left'), | |
frameon=True, loc=9, borderpad=0.75) | |
at.patch.set_boxstyle("round, pad=0.2, rounding_size=0.25") | |
ax.add_artist(at) | |
at = AnchoredText(title, prop=dict(size=fsize, ha='center'), | |
frameon=True, loc=9, borderpad=5) | |
at.patch.set_boxstyle("round, pad=0.2, rounding_size=0.25") | |
ax.add_artist(at) | |
at = AnchoredText(title, prop=dict(size=fsize, ha='right'), | |
frameon=True, loc=9, borderpad=9) | |
at.patch.set_boxstyle("round, pad=0.2, rounding_size=0.25") | |
ax.add_artist(at) | |
fig = plt.figure(figsize=(8,12)) | |
ax1 = fig.add_subplot(311) | |
locator = divider.make_axes_locatable(ax1) | |
cax1 = locator.append_axes("right", size="5%", pad="3%") | |
plt.draw() | |
add_center_text(ax1) | |
ax1.grid() | |
ax2 = fig.add_subplot(312) | |
locator = divider.make_axes_locatable(ax2) | |
cax2 = locator.append_axes("right", size="5%", pad="3%") | |
plt.draw() | |
add_center_text_alt(locator, ax2) | |
ax2.grid() | |
ax3 = fig.add_subplot(313) | |
locator = divider.make_axes_locatable(ax3) | |
cax3 = locator.append_axes("right", size="5%", pad="3%") | |
plt.draw() | |
add_center_text_alt2(ax3) | |
ax3.grid() | |
plt.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment