在matplotlib图中枚举图
在matplotlib图中,我想用a)、b)、c)等来列举所有(子)图。有没有一种方法可以自动做到这一点 到目前为止,我使用的是单个绘图的标题,但这远远不是理想的,因为我希望数字左对齐,而可选的真实标题应该位于图形的中心在matplotlib图中枚举图,matplotlib,title,enumerate,Matplotlib,Title,Enumerate,在matplotlib图中,我想用a)、b)、c)等来列举所有(子)图。有没有一种方法可以自动做到这一点 到目前为止,我使用的是单个绘图的标题,但这远远不是理想的,因为我希望数字左对齐,而可选的真实标题应该位于图形的中心 import string from itertools import cycle from six.moves import zip def label_axes(fig, labels=None, loc=None, **kwargs): """ Walk
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.ascii_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()
这对我来说似乎很有用,所以我把它放在了一个要点中:我编写了一个函数来自动执行此操作,其中标签作为图例引入:
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
。上面的脚本给出了这样的图:
一个超级快速的方法是利用
chr()
将整数转换为字符这一事实。因此,可以执行以下操作:
导入matplotlib.pyplot作为plt
图,axs=plt子批次(2,2)
对于i,枚举中的ax(axs.flat,start=97):
ax.图([0,1],[0,1])
ax.text(0.05,0.9,chr(i)+'),transform=ax.transAxes)
产生:
作为旁注,每个轴实际上都有三个标题(左、右、中),但我不记得这是在1.3版中还是在master上。