matplotlib源码解析标题实现(窗⼝标题,标题,⼦图标题不同之间的差异)
在matplotlib中常⽤的标题主要三种:窗⼝标题、图像标题和⼦图标题。
先通过三个案例简要说明这三类标题的实现。
窗⼝标题、图像标题,⼦图标题(仅1个⼦图)
import matplotlib.pyplot as plt
fig = plt.figure()
plt.plot([1,2])
# 设置图像标题
plt.suptitle("这是图像标题")
# 设置⼦图标题
plt.title("这是⼦图标题")
# 获取默认窗⼝标题
current_title = fig.canvas.manager.window.windowTitle()
print("默认窗⼝:",current_title)
# 设置窗⼝标题⽅式⼀
fig.canvas.set_window_title("这是窗⼝标题")
# 设置窗⼝标题⽅式⼆
fig.canvas.manager.window.setWindowTitle("这是窗⼝标题")
plt.show()
窗⼝标题、图像标题、⼦图标题(多⼦图)
使⽤subplot函数实现⼦图
import matplotlib.pyplot as plt
fig = plt.figure()
plt.subplot(1,2,1)
plt.plot([1,2,3,4],[1,4,9,16],"go")
# 设置⼦图1标题
plt.title("⼦图1标题")
plt.subplot(122)
plt.plot([1,2,3,4],[1,4,9,16],"r^")# r^ 表⽰红⾊(red)三⾓
# 设置⼦图2标题
plt.title("⼦图2标题")
# 设置图像标题
plt.suptitle("图像标题")
# 设置窗⼝标题
#fig.canvas.set_window_title("这是窗⼝标题")
fig.canvas.manager.window.setWindowTitle("这是窗⼝标题") plt.show()
使⽤subplots函数subplots实现⼦图
import matplotlib.pyplot as plt
fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(6,6))
ax[0].plot([1,2,3,4],[1,4,9,16],"go")
# 设置⼦图1标题
ax[0].set_title("⼦图1标题")
ax[1].plot([1,2,3,4],[1,4,9,16],"r^")
# 设置⼦图2标题
ax[1].set_title("⼦图2标题")
# 设置图像标题
plt.suptitle("图像标题")
# 设置窗⼝标题
fig.canvas.manager.window.setWindowTitle("这是窗⼝标题")
plt.show()
原理分析
通过前⾯三个案例可知:
窗⼝标题
设置窗⼝标题可以⽤两种⽅法:
⼀种是调⽤figure.canvas对象的set_window_title⽅法,⼀种是figure.canvas.manager.window对象的setWindowTitle⽅法。通过下⾯源码可知,这两种⽅法其实是等价的。
因此在⽇常实现过程中,关键是获取当前图像对象(figure),即案例中的fig。该⽅法只有⼀个参数,类型为字符串。
可以通过
通过figure.canvas.manager.window对象的windowTitle⽅法可以获取窗⼝标题。
class FigureManagerQT(FigureManagerBase):
def set_window_title(self, title):
self.window.setWindowTitle(title)
图像标题
调⽤plt.suptitle函数即可。根据源码可知,plt.suptitle函数其实是调⽤了当前figure对象的suptitle⽅法。
suptitle函数参数
def suptitle(self, t,**kwargs):
"""
Add a centered title to the figure.
Parameters
-
---------
t : str
The title text.
x : float, default 0.5
The x location of the text in figure coordinates.
y : float, default 0.98
The y location of the text in figure coordinates.
horizontalalignment, ha : {'center', 'left', right'}, default: 'center'
The horizontal alignment of the text relative to (*x*, *y*).
verticalalignment, va : {'top', 'center', 'bottom', 'baseline'}, \
default: 'top'
The vertical alignment of the text relative to (*x*, *y*).
fontsize, size : default: :rc:`figure.titlesize`
The font size of the text. See `.Text.set_size` for possible
values.
fontweight, weight : default: :rc:`figure.titleweight`
The font weight of the text. See `.Text.set_weight` for possiblematplotlib中subplot
values.
Returns
-------
text
The `.Text` instance of the title.
Other Parameters
----------------
fontproperties : None or dict, optional
A dict of font properties. If *fontproperties* is given the
default values for font size and weight are taken from the
`.FontProperties` defaults. :rc:`figure.titlesize` and
:rc:`figure.titleweight` are ignored in this case.
**kwargs
Additional kwargs are `Text` properties.
Examples
--------
>>> fig.suptitle('This is the figure title', fontsize=12)
"""
⼦图标题
使⽤subplot函数:在所在⼦图中,使⽤plt.title函数。
使⽤subplots函数:使⽤⼦图对象调⽤set_title⽅法。
plt.title函数和axes.set_title⽅法的参数相同。
注意,在使⽤subplots函数创建⼦图时,为什么不能使⽤plt.title函数设置⼦图标题呢?
根据title函数的源码可知,title函数其实是通过gca()函数获取⼦图,然后再调⽤set_title⽅法设置标题的。根据实验,在使⽤subplots函数函数创建多个⼦图时,a()只能得到最后⼀个⼦图的标题,因此,在某些情况下使⽤plt.title函数可设置最后⼀个⼦图的标题。
plt.title函数和axes.set_title⽅法源码
def title(label, fontdict=None, loc=None, pad=None,*, y=None,**kwargs):
return gca().set_title(
label, fontdict=fontdict, loc=loc, pad=pad, y=y,**kwargs)
Axes.set_title(self, label, fontdict=None, loc=None, pad=None,*, y=None,**kwargs): """
Set a title for the axes.
Set one of the three available axes titles. The available titles
are positioned above the axes in the center, flush with the left
edge, and flush with the right edge.
Parameters
----------
label : str
Text to use for the title
fontdict : dict
A dictionary controlling the appearance of the title text,
the default *fontdict* is::
{'fontsize': rcParams['axes.titlesize'],
'fontweight': rcParams['axes.titleweight'],
'color': rcParams['axes.titlecolor'],
'verticalalignment': 'baseline',
'horizontalalignment': loc}
loc : {'center', 'left', 'right'}, default: :rc:`axes.titlelocation`
Which title to set.
y : float, default: :rc:`axes.titley`
Vertical axes loation for the title (1.0 is the top).  If
None (the default), y is determined automatically to avoid
decorators on the axes.
pad : float, default: :rc:`axes.titlepad`
The offset of the title from the top of the axes, in points.
Returns
-------
`.Text`
The matplotlib text instance representing the title
Other Parameters
----------------
**kwargs : `.Text` properties
Other keyword arguments are text properties, see `.Text` for a list
of valid text properties.
"""
import matplotlib.pyplot as plt
fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(6,6))
ax[0].plot([1,2,3,4],[1,4,9,16],"go")
ax[1].plot([1,2,3,4],[1,4,9,16],"r^")
a())
print(ax[0],ax[1])
结果为
AxesSubplot(0.547727,0.11;0.352273x0.77)
AxesSubplot(0.125,0.11;0.352273x0.77) AxesSubplot(0.547727,0.11;0.352273x0.77)

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。