在matplotlib图中,我想枚举所有(子)图a),b),c)等等。有没有办法自动做到这一点?枚举matplotlib中的图块
到目前为止,我使用的是单个地块的标题,但这并不理想,因为我希望数字左对齐,而可选的真实标题应该以图形为中心。
在matplotlib图中,我想枚举所有(子)图a),b),c)等等。有没有办法自动做到这一点?枚举matplotlib中的图块
到目前为止,我使用的是单个地块的标题,但这并不理想,因为我希望数字左对齐,而可选的真实标题应该以图形为中心。
import string
from itertools import cycle
from six.moves import zip
def label_axes(fig, labels=None, loc=None, **kwargs):
"""
Walks through axes and labels each.
kwargs are collected and passed to `annotate`
Parameters
----------
fig : Figure
Figure object to work on
labels : iterable or None
iterable of strings to use to label the axes.
If None, lower case letters are used.
loc : len=2 tuple of floats
Where to put the label in axes-fraction units
"""
if labels is None:
labels = string.lowercase
# re-use labels rather than stop labeling
labels = cycle(labels)
if loc is None:
loc = (.9, .9)
for ax, lab in zip(fig.axes, labels):
ax.annotate(lab, xy=loc,
xycoords='axes fraction',
**kwargs)
用法示例:
from matplotlib import pyplot as plt
fig, ax_lst = plt.subplots(3, 3)
label_axes(fig, ha='right')
plt.draw()
fig, ax_lst = plt.subplots(3, 3)
label_axes(fig, ha='left')
plt.draw()
这似乎有用足够,我认为我把这个在一个要点:https://gist.github.com/tacaswell/9643166
我写了一个函数来自动执行此操作,在引入标签作为一个传说:
import numpy
import matplotlib.pyplot as plt
def setlabel(ax, label, loc=2, borderpad=0.6, **kwargs):
legend = ax.get_legend()
if legend:
ax.add_artist(legend)
line, = ax.plot(numpy.NaN,numpy.NaN,color='none',label=label)
label_legend = ax.legend(handles=[line],loc=loc,handlelength=0,handleheight=0,handletextpad=0,borderaxespad=0,borderpad=borderpad,frameon=False,**kwargs)
label_legend.remove()
ax.add_artist(label_legend)
line.remove()
fig,ax = plt.subplots()
ax.plot([1,2],[1,2])
setlabel(ax, '(a)')
plt.show()
该标签的位置可以控制用loc
参数进行填充,可以用borderpad
参数(负值将标签推到图的外部)来控制与轴的距离,还可以使用其他可用于legend
的选项,例如fontsize
。上面的脚本给出了这样的数字:
作为一个方面说明,每个轴实际上有三个标题(左,右,中),但我不记得它是在1.3还是只在主。 – tacaswell