【问题标题】:Enumerate plots in matplotlib figure枚举matplotlib图中的图
【发布时间】:2014-04-25 20:36:57
【问题描述】:

在 matplotlib 图中,我想用 a)、b)、c) 等枚举所有(子)图。有没有办法自动做到这一点?

到目前为止,我使用了各个地块的标题,但这远非理想,因为我希望数字左对齐,而可选的真实标题应以图为中心。

【问题讨论】:

  • 附带说明,每个轴实际上都有三个标题(左、右、中),但我不记得那是在 1.3 中还是仅在 master 上。

标签: matplotlib title enumerate


【解决方案1】:
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()

这对我来说似乎很有用,我把它放在一个要点中:https://gist.github.com/tacaswell/9643166

【讨论】:

    【解决方案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参数控制(负值将标签推到图形之外),其他选项可用于@987654326 @也可以使用,如fontsize。上面的脚本给出了这样的图:

    【讨论】:

      【解决方案3】:

      一个超级快速的方法是利用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)
      

      产生:

      【讨论】:

        猜你喜欢
        • 2011-05-09
        • 2010-09-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-26
        • 1970-01-01
        • 2017-05-09
        相关资源
        最近更新 更多