如何在Matplotlib中设置图形标题和轴标签的字体大小?

问题:如何在Matplotlib中设置图形标题和轴标签的字体大小?

我正在Matplotlib中创建一个图形,如下所示:

from matplotlib import pyplot as plt

fig = plt.figure()
plt.plot(data)
fig.suptitle('test title')
plt.xlabel('xlabel')
plt.ylabel('ylabel')
fig.savefig('test.jpg')

我想为图形标题和轴标签指定字体大小。我需要所有三个字体大小都不同,所以我不需要设置全局字体大小(mpl.rcParams['font.size']=x)。如何分别设置图形标题和轴标签的字体大小?

I am creating a figure in Matplotlib like this:

from matplotlib import pyplot as plt

fig = plt.figure()
plt.plot(data)
fig.suptitle('test title')
plt.xlabel('xlabel')
plt.ylabel('ylabel')
fig.savefig('test.jpg')

I want to specify font sizes for the figure title and the axis labels. I need all three to be different font sizes, so setting a global font size (mpl.rcParams['font.size']=x) is not what I want. How do I set font sizes for the figure title and the axis labels individually?


回答 0

对付像文本功能labeltitle等接受参数相同matplotlib.text.Text。对于字体大小,您可以使用size/fontsize

from matplotlib import pyplot as plt    

fig = plt.figure()
plt.plot(data)
fig.suptitle('test title', fontsize=20)
plt.xlabel('xlabel', fontsize=18)
plt.ylabel('ylabel', fontsize=16)
fig.savefig('test.jpg')

对于全局设置titlelabel大小,mpl.rcParams包含axes.titlesizeaxes.labelsize。(来自页面):

axes.titlesize      : large   # fontsize of the axes title
axes.labelsize      : medium  # fontsize of the x any y labels

(据我所知,没有办法分别设置xy标记尺寸。)

而且我看到那axes.titlesize没有影响suptitle。我想,您需要手动设置。

Functions dealing with text like label, title, etc. accept parameters same as matplotlib.text.Text. For the font size you can use size/fontsize:

from matplotlib import pyplot as plt    

fig = plt.figure()
plt.plot(data)
fig.suptitle('test title', fontsize=20)
plt.xlabel('xlabel', fontsize=18)
plt.ylabel('ylabel', fontsize=16)
fig.savefig('test.jpg')

For globally setting title and label sizes, mpl.rcParams contains axes.titlesize and axes.labelsize. (From the page):

axes.titlesize      : large   # fontsize of the axes title
axes.labelsize      : medium  # fontsize of the x any y labels

(As far as I can see, there is no way to set x and y label sizes separately.)

And I see that axes.titlesize does not affect suptitle. I guess, you need to set that manually.


回答 1

您也可以通过rcParams字典全局执行此操作:

import matplotlib.pylab as pylab
params = {'legend.fontsize': 'x-large',
          'figure.figsize': (15, 5),
         'axes.labelsize': 'x-large',
         'axes.titlesize':'x-large',
         'xtick.labelsize':'x-large',
         'ytick.labelsize':'x-large'}
pylab.rcParams.update(params)

You can also do this globally via a rcParams dictionary:

import matplotlib.pylab as pylab
params = {'legend.fontsize': 'x-large',
          'figure.figsize': (15, 5),
         'axes.labelsize': 'x-large',
         'axes.titlesize':'x-large',
         'xtick.labelsize':'x-large',
         'ytick.labelsize':'x-large'}
pylab.rcParams.update(params)

回答 2

如果您更习惯于使用ax对象进行绘图,则可能会ax.xaxis.label.set_size()更容易记住,或者至少在ipython终端中使用tab会更容易找到。看到效果后似乎需要重新绘制操作。例如:

import matplotlib.pyplot as plt

# set up a plot with dummy data
fig, ax = plt.subplots()
x = [0, 1, 2]
y = [0, 3, 9]
ax.plot(x,y)

# title and labels, setting initial sizes
fig.suptitle('test title', fontsize=12)
ax.set_xlabel('xlabel', fontsize=10)
ax.set_ylabel('ylabel', fontsize='medium')   # relative to plt.rcParams['font.size']

# setting label sizes after creation
ax.xaxis.label.set_size(20)
plt.draw()

我不知道创建字幕后设置字幕大小的类似方法。

If you’re more used to using ax objects to do your plotting, you might find the ax.xaxis.label.set_size() easier to remember, or at least easier to find using tab in an ipython terminal. It seems to need a redraw operation after to see the effect. For example:

import matplotlib.pyplot as plt

# set up a plot with dummy data
fig, ax = plt.subplots()
x = [0, 1, 2]
y = [0, 3, 9]
ax.plot(x,y)

# title and labels, setting initial sizes
fig.suptitle('test title', fontsize=12)
ax.set_xlabel('xlabel', fontsize=10)
ax.set_ylabel('ylabel', fontsize='medium')   # relative to plt.rcParams['font.size']

# setting label sizes after creation
ax.xaxis.label.set_size(20)
plt.draw()

I don’t know of a similar way to set the suptitle size after it’s created.


回答 3

为了只修改标题的字体(而不是轴的字体),我使用了以下命令:

import matplotlib.pyplot as plt
fig = plt.Figure()
ax = fig.add_subplot(111)
ax.set_title('My Title', fontdict={'fontsize': 8, 'fontweight': 'medium'})

fontdict接受matplotlib.text.Text中的所有kwarg 。

To only modify the title’s font (and not the font of the axis) I used this:

import matplotlib.pyplot as plt
fig = plt.Figure()
ax = fig.add_subplot(111)
ax.set_title('My Title', fontdict={'fontsize': 8, 'fontweight': 'medium'})

The fontdict accepts all kwargs from matplotlib.text.Text.


回答 4

根据官方指南pylab不再建议使用。matplotlib.pyplot应该直接使用。

在全球范围内设置字体大小通过rcParams应该做

import matplotlib.pyplot as plt
plt.rcParams['axes.labelsize'] = 16
plt.rcParams['axes.titlesize'] = 16

# or

params = {'axes.labelsize': 16,
          'axes.titlesize': 16}
plt.rcParams.update(params)

# or

import matplotlib as mpl
mpl.rc('axes', labelsize=16, titlesize=16)

# or 

axes = {'labelsize': 16,
        'titlesize': 16}
mpl.rc('axes', **axes)

可以使用以下命令恢复默认值

plt.rcParams.update(plt.rcParamsDefault)

您还可以通过在matplotlib配置目录下的目录中创建样式表来完成此操作(您可以从中获取配置目录)。样式表格式为stylelibmatplotlib.get_configdir()

axes.labelsize: 16
axes.titlesize: 16

如果您有样式表,/path/to/mpl_configdir/stylelib/mystyle.mplstyle则可以通过

plt.style.use('mystyle')

# or, for a single section

with plt.style.context('mystyle'):
    # ...

您还可以创建(或修改)matplotlibrc文件共享格式

axes.labelsize = 16
axes.titlesize = 16

取决于您修改的matplotlibrc文件,这些更改将仅用于当前工作目录,具有matplotlibrc文件的所有工作目录,或具有matplotlibrc文件且没有其他matplotlibrc文件的所有工作目录。被指定。看到本节更多详细信息,定制matplotlib页面的。

rcParams可以通过找到完整的键列表plt.rcParams.keys(),但是要调整字体大小,请使用(此处引号为斜体)

  • axes.labelsizex和y标签的字体大小
  • axes.titlesize轴标题的字体大小
  • figure.titlesize图形标题的大小(Figure.suptitle()
  • xtick.labelsize刻度标签的字体大小
  • ytick.labelsize刻度标签的字体大小
  • legend.fontsize-图例的字体大小(plt.legend()fig.legend()
  • legend.title_fontsize-图例标题的字体大小,None设置为与默认轴相同。有关用法示例,请参见此答案

所有这些都接受字符串大小{'xx-small', 'x-small', 'smaller', 'small', 'medium', 'large', 'larger', 'x-large', 'xxlarge'}floatin pt。字符串大小是相对于默认字体大小定义的,该默认大小由

  • font.size文本的默认字体大小,以pts为单位。标准值为10点

此外,可以通过以下方式指定重量(尽管仅用于默认值)

  • font.weight-所使用的字体的默认粗细text.Text。接受{100, 200, 300, 400, 500, 600, 700, 800, 900}'normal'(400),'bold'(700)'lighter',和'bolder'相对于当前重量)。

Per the official guide, use of pylab is no longer recommended. matplotlib.pyplot should be used directly instead.

Globally setting font sizes via rcParams should be done with

import matplotlib.pyplot as plt
plt.rcParams['axes.labelsize'] = 16
plt.rcParams['axes.titlesize'] = 16

# or

params = {'axes.labelsize': 16,
          'axes.titlesize': 16}
plt.rcParams.update(params)

# or

import matplotlib as mpl
mpl.rc('axes', labelsize=16, titlesize=16)

# or 

axes = {'labelsize': 16,
        'titlesize': 16}
mpl.rc('axes', **axes)

The defaults can be restored using

plt.rcParams.update(plt.rcParamsDefault)

You can also do this by creating a style sheet in the stylelib directory under the matplotlib configuration directory (you can get your configuration directory from matplotlib.get_configdir()). The style sheet format is

axes.labelsize: 16
axes.titlesize: 16

If you have a style sheet at /path/to/mpl_configdir/stylelib/mystyle.mplstyle then you can use it via

plt.style.use('mystyle')

# or, for a single section

with plt.style.context('mystyle'):
    # ...

You can also create (or modify) a matplotlibrc file which shares the format

axes.labelsize = 16
axes.titlesize = 16

Depending on which matplotlibrc file you modify these changes will be used for only the current working directory, for all working directories which do not have a matplotlibrc file, or for all working directories which do not have a matplotlibrc file and where no other matplotlibrc file has been specified. See this section of the customizing matplotlib page for more details.

A complete list of the rcParams keys can be retrieved via plt.rcParams.keys(), but for adjusting font sizes you have (italics quoted from here)

  • axes.labelsizeFontsize of the x and y labels
  • axes.titlesizeFontsize of the axes title
  • figure.titlesizeSize of the figure title (Figure.suptitle())
  • xtick.labelsizeFontsize of the tick labels
  • ytick.labelsizeFontsize of the tick labels
  • legend.fontsize – Fontsize for legends (plt.legend(), fig.legend())
  • legend.title_fontsize – Fontsize for legend titles, None sets to the same as the default axes. See this answer for usage example.

all of which accept string sizes {'xx-small', 'x-small', 'smaller', 'small', 'medium', 'large', 'larger', 'x-large', 'xxlarge'} or a float in pt. The string sizes are defined relative to the default font size which is specified by

  • font.sizethe default font size for text, given in pts. 10 pt is the standard value

Additionally, the weight can be specified (though only for the default it appears) by

  • font.weight – The default weight of the font used by text.Text. Accepts {100, 200, 300, 400, 500, 600, 700, 800, 900} or 'normal' (400), 'bold' (700), 'lighter', and 'bolder' (relative with respect to current weight).

回答 5

更改字体大小的另一种方法是更改​​填充。当Python保存您的PNG时,您可以使用打开的对话框更改布局。轴之间的间距,如果需要,可以更改内边距。

An alternative solution to changing the font size is to change the padding. When Python saves your PNG, you can change the layout using the dialogue box that opens. The spacing between the axes, padding if you like can be altered at this stage.


回答 6

放在right_ax之前set_ylabel()

ax.right_ax.set_ylabel('AB scale')

Place right_ax before set_ylabel()

ax.right_ax.set_ylabel('AB scale')


回答 7

7(最佳解决方案)

 from numpy import*
 import matplotlib.pyplot as plt
 X = linspace(-pi, pi, 1000)

class Crtaj:

    def nacrtaj(self,x,y):
         self.x=x
         self.y=y
         return plt.plot (x,y,"om")

def oznaci(self):
    return plt.xlabel("x-os"), plt.ylabel("y-os"), plt.grid(b=True)

6(较差的解决方案)

from numpy import*
M = array([[3,2,3],[1,2,6]])
class AriSred(object):
    def __init__(self,m):
    self.m=m

def srednja(self):
    redovi = len(M)
    stupci = len (M[0])
    lista=[]
    a=0
    suma=0
    while a<stupci:
        for i in range (0,redovi):
            suma=suma+ M[i,a]
        lista.append(suma)
        a=a+1
        suma=0
    b=array(lista) 
    b=b/redovi
    return b



OBJ = AriSred(M)
sr = OBJ.srednja()

7 (best solution)

 from numpy import*
 import matplotlib.pyplot as plt
 X = linspace(-pi, pi, 1000)

class Crtaj:

    def nacrtaj(self,x,y):
         self.x=x
         self.y=y
         return plt.plot (x,y,"om")

def oznaci(self):
    return plt.xlabel("x-os"), plt.ylabel("y-os"), plt.grid(b=True)

6 (slightly worse solution)

from numpy import*
M = array([[3,2,3],[1,2,6]])
class AriSred(object):
    def __init__(self,m):
    self.m=m

def srednja(self):
    redovi = len(M)
    stupci = len (M[0])
    lista=[]
    a=0
    suma=0
    while a<stupci:
        for i in range (0,redovi):
            suma=suma+ M[i,a]
        lista.append(suma)
        a=a+1
        suma=0
    b=array(lista) 
    b=b/redovi
    return b



OBJ = AriSred(M)
sr = OBJ.srednja()