79

我想给我的图表一个 18pt 大字体的标题,然后在它下面的一个较小的 10pt 字体的字幕。如何在 matplotlib 中执行此操作?看来该title()函数只接受一个具有单个fontsize属性的单个字符串。必须有一种方法可以做到这一点,但是如何呢?

4

7 回答 7

91

我所做的是使用title()副标题和suptitle() 主标题的功能(它们可以采用不同的字体大小参数)。希望有帮助!

于 2010-12-20T14:56:27.513 回答
38

尽管这并没有为您提供与多种字体大小相关的灵活性,但在 pyplot.title() 字符串中添加换行符可能是一个简单的解决方案;

plt.title('Really Important Plot\nThis is why it is important')
于 2012-09-18T23:26:09.247 回答
29

这是一个实现 Floris van Vugt 的回答(2010 年 12 月 20 日)的 pandas 代码示例。他说:

>我所做的是对副标题使用 title() 函数,对主标题使用 suptitle() 函数(它们可以采用不同的字体大小参数)。希望有帮助!

import pandas as pd
import matplotlib.pyplot as plt

d = {'series a' : pd.Series([1., 2., 3.], index=['a', 'b', 'c']),
      'series b' : pd.Series([1., 2., 3., 4.], index=['a', 'b', 'c', 'd'])}
df = pd.DataFrame(d)

title_string = "This is the title"
subtitle_string = "This is the subtitle"

plt.figure()
df.plot(kind='bar')
plt.suptitle(title_string, y=1.05, fontsize=18)
plt.title(subtitle_string, fontsize=10)

注意:我无法评论该答案,因为我是 stackoverflow 的新手。

于 2015-02-24T21:04:04.050 回答
21

我认为没有任何内置功能,但您可以通过在轴上方留出更多空间并使用figtext

axes([.1,.1,.8,.7])
figtext(.5,.9,'Foo Bar', fontsize=18, ha='center')
figtext(.5,.85,'Lorem ipsum dolor sit amet, consectetur adipiscing elit',fontsize=10,ha='center')

ha是 的缩写horizontalalignment

于 2009-09-07T16:38:49.803 回答
16

对我有用的解决方案是:

  • 用于suptitle()实际标题
  • 用于title()字幕并使用可选参数进行调整y
    import matplotlib.pyplot as plt
    """
            some code here
    """
    plt.title('My subtitle',fontsize=16)
    plt.suptitle('My title',fontsize=24, y=1)
    plt.show()

两段文本之间可能会有一些令人讨厌的重叠。您可以通过摆弄 的值来解决此问题,y直到您正确为止。

于 2019-02-23T14:57:07.540 回答
15

只需使用 TeX !这有效:

title(r"""\Huge{Big title !} \newline \tiny{Small subtitle !}""")

编辑:要启用 TeX 处理,您需要将“usetex = True”行添加到 matplotlib 参数:

fig_size = [12.,7.5]
params = {'axes.labelsize': 8,
      'text.fontsize':   6,
      'legend.fontsize': 7,
      'xtick.labelsize': 6,
      'ytick.labelsize': 6,
      'text.usetex': True,       # <-- There 
      'figure.figsize': fig_size,
      }
rcParams.update(params)

我想您还需要在您的计算机上运行 TeX 发行版。此页面提供了所有详细信息:

http://matplotlib.org/users/usetex.html

于 2014-09-05T11:53:57.770 回答
1

正如这里提到的,你可以使用matplotlib.pyplot.text对象来达到相同的结果:

plt.text(x=0.5, y=0.94, s="My title 1", fontsize=18, ha="center", transform=fig.transFigure)
plt.text(x=0.5, y=0.88, s= "My title 2 in different size", fontsize=12, ha="center", transform=fig.transFigure)
plt.subplots_adjust(top=0.8, wspace=0.3)
于 2020-09-07T08:31:28.690 回答