您可以直接应用中提供的解决方案
How do I make the width of the title box span the entire plot?
只需稍作修改,就可以使用图形宽度而不是子图宽度作为子图的水平大小。
import matplotlib.pyplot as plt
from matplotlib.path import Path
from matplotlib.patches import BoxStyle
class ExtendedTextBox(BoxStyle._Base):
"""
An Extended Text Box that expands to the axes limits
if set in the middle of the axes
"""
def __init__(self, pad=0.3, width=500.):
"""
width:
width of the textbox.
Use `ax.get_window_extent().width`
to get the width of the axes.
pad:
amount of padding (in vertical direction only)
"""
self.width=width
self.pad = pad
super(ExtendedTextBox, self).__init__()
def transmute(self, x0, y0, width, height, mutation_size):
"""
x0 and y0 are the lower left corner of original text box
They are set automatically by matplotlib
"""
# padding
pad = mutation_size * self.pad
# we add the padding only to the box height
height = height + 2.*pad
# boundary of the padded box
y0 = y0 - pad
y1 = y0 + height
_x0 = x0
x0 = _x0 +width /2. - self.width/2.
x1 = _x0 +width /2. + self.width/2.
cp = [(x0, y0),
(x1, y0), (x1, y1), (x0, y1),
(x0, y0)]
com = [Path.MOVETO,
Path.LINETO, Path.LINETO, Path.LINETO,
Path.CLOSEPOLY]
path = Path(cp, com)
return path
# register the custom style
BoxStyle._style_list["ext"] = ExtendedTextBox
fig, ax = plt.subplots()
# set the title position to the horizontal center (0.5) of the axes
title = fig.suptitle('My Log Normal Example', position=(.5, 0.96),
backgroundcolor='black', color='white')
# set the box style of the title text box to our custom box
bb = title.get_bbox_patch()
def resize(event):
# use the figure width as width of the text box
bb.set_boxstyle("ext", pad=0.4, width=fig.get_size_inches()[0]*fig.dpi )
resize(None)
# Optionally: use eventhandler to resize the title box, in case the window is resized
cid = plt.gcf().canvas.mpl_connect('resize_event', resize)
# use the same dpi for saving to file as for plotting on screen
plt.savefig(__file__+".png", dpi="figure")
plt.show()