在matplotlib图中,我想用a),b),c)枚举所有(子)图,依此类推。有没有办法自动执行此操作?
到目前为止,我使用了各个图表的标题,但这远非理想,因为我希望数字保持对齐,而可选的实际标题应该以图形为中心。
答案 0 :(得分:7)
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
答案 1 :(得分:2)
我写了一个自动执行此操作的函数,其中标签作为图例引入:
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
。上面的脚本给出了这样的数字:
答案 2 :(得分:0)
一种超快速的方法是利用chr()
将整数转换为字符的事实。自a-z fall in the range 97-122起,您可以执行以下操作:
import matplotlib.pyplot as plt
fig,axs = plt.subplots(2,2)
for i,ax in enumerate(axs.flat, start=97):
ax.plot([0,1],[0,1])
ax.text(0.05,0.9,chr(i)+')', transform=ax.transAxes)
产生: