在matplotlib中拆分图形的标题

时间:2011-12-22 00:40:43

标签: matplotlib

我使用matplotlib创建一个包含4个子图的图形。

我想拆分一个子图的标题,这样每条线都会在子画面的中心位置。

我试过

import matplotlib.pylab as plt

fig = plt.figure(num=0,figsize=(8.27, 11.69), dpi=300)
ax  = fig.add_subplot(2, 2, 1)
ax.set_title(r'Normalized occupied \\ Neighbors')

我得到的是Neighbors左侧缩进。

我怎么能纠正这个?

5 个答案:

答案 0 :(得分:35)

当我以这种方式格式化字符串时,我得到了正确的对齐方式:

import matplotlib.pylab as plt

fig = plt.figure()#num=0,figsize=(8.27, 11.69), dpi=300)
ax  = fig.add_subplot(2, 2, 1)
ax.set_title('Normalized occupied \n Neighbors')

plt.show()

enter image description here

答案 1 :(得分:11)

r前缀兼容的更好的解决方案(特别是当需要使用LaTeX标记时)是将标题文本分成两个(或更多部分),例如,

import matplotlib.pylab as plt

fig = plt.figure()
plt.title('My Title\n' + r'$\alpha - \omega$ are LaTeX Markup')
plt.plot([1,2,3,4])
plt.show()

答案 2 :(得分:1)

我知道这个问题有点老了,但对于其他需要参考的问题-在Matplotlib 3.1.1中,plt.title()和ax.set_title()都允许将Text Properties作为kwarg传递,因此您可以拥有

(1,'John','Illinois'), (2,'Peter','Los Angeles'), (3,'Chris','Dallas')

plt.title('My very long title that I want to wrap and stay center-aligned', wrap=True)

答案 3 :(得分:0)

除了之前的答案,如果有人想要自动化操作,我已编写了一个函数来简化这一过程。 这是它:

def split_title_line(title_text, split_on='(', max_words=5):  # , max_words=None):
    """
    A function that splits any string based on specific character
    (returning it with the string), with maximum number of words on it
    """
    split_at = title_text.find (split_on)
    ti = title_text
    if split_at > 1:
        ti = ti.split (split_on)
        for i, tx in enumerate (ti[1:]):
            ti[i + 1] = split_on + tx
    if type (ti) == type ('text'):
        ti = [ti]
    for j, td in enumerate (ti):
        if td.find (split_on) > 0:
            pass
        else:
            tw = td.split ()
            t2 = []
            for i in range (0, len (tw), max_words):
                t2.append (' '.join (tw[i:max_words + i]))
            ti[j] = t2
    ti = [item for sublist in ti for item in sublist]
    ret_tex = []
    for j in range (len (ti)):
        for i in range(0, len(ti)-1, 2):
            if len (ti[i].split()) + len (ti[i+1].split ()) <= max_words:
                mrg = " ".join ([ti[i], ti[i+1]])
                ti = [mrg] + ti[2:]
                break

    if len (ti[-2].split ()) + len (ti[-1].split ()) <= max_words:
        mrg = " ".join ([ti[-2], ti[-1]])
        ti = ti[:-2] + [mrg]
    return '\n'.join (ti)

<强>示例:

split_title_line ('Primary school completion (% of girls)')

<强> 出:

Primary school completion 
(% of girls)

在: split_title_line ('Primary school completion in the country as % of girls') 输出:

Primary school completion in the
country as % of girls

有关在matplotlib中拆分标题的问题,可以添加此ax.set_title(split_title_line(r'Normalized occupied Neighbors', max_words=2))

希望每个人都能从中受益。

答案 4 :(得分:0)

只想加上我的2美分:这是一个更普遍的问题,围绕正确地插入换行符以将文本从一条长行分解成视觉上令人愉悦的美观块的问题。因此,这是我的贡献,与Mohammed的贡献非常相似,只是将字符串分成5个单词的块。根据您的需要对其进行自定义应该很简单(分隔符,长度等)

def pretty_name(text):
  words = text.split("_")
  total_string = ""
  for counter, word in enumerate(words):
    if counter>0 and counter % 5 == 0:
      total_string +="\n{}".format(word)
    else:
      total_string +=" {}".format(word)
  return total_string.lstrip()