Matplotlib 简明教程

Matplotlib - Fonts

字体在自定义绘图中的文本元素方面发挥着至关重要的作用。我们可以控制字体样式、大小、系列和其他属性,以增强可视化中文本的外观和可读性。

Fonts play a crucial role in customizing text elements within plots. We can control font styles, sizes, families and other properties to enhance the appearance and readability of text in our visualizations.

在 Matplotlib 库中, ‘Fonts’ 引用用于在绘图和可视化中呈现文本的字体。字体在自定义标签、标题、注释和绘图中图例等文本元素的外观方面发挥着重要作用。

In Matplotlib library ‘Fonts’ refer to the typefaces used for rendering text in plots and visualizations. Fonts play a significant role in customizing the appearance of text elements such as labels, titles, annotations and legends within plots.

Key Aspects of Fonts in Matplotlib library

  1. Font Family − Refers to the style or category of the font. Common font families include serif, sans-serif, monospace etc. Each family has its own visual characteristics.

  2. Font Style − Determines the appearance of text such as normal, italic or oblique.

  3. Font Weight − Specifies the thickness or boldness of the font ranging from normal to various levels of boldness.

Controlling Fonts in Matplotlib

  1. Setting Font Properties − We can control font properties for text elements in plots using parameters such as fontsize, fontstyle, fontweight and fontfamily in the functions such as plt.xlabel(), plt.title() etc.

plt.xlabel('X-axis Label',
   fontsize=12, fontstyle='italic',
	fontweight='bold', fontfamily='serif')
  1. Global Font Configuration − Adjusting font properties globally for the entire plot using plt.rcParams allows us to set default font settings for consistency.

plt.rcParams['font.family'] = 'sans-serif'
plt.rcParams['font.size'] = 12

Importance of Fonts in Visualization

  1. Readability − The choice of fonts significantly impacts the readability of text elements in plots. Selecting appropriate fonts improves the clarity of visualized information.

  2. Aesthetics − Fonts contribute to the overall aesthetics of the plot by affecting its visual appeal and presentation.

  3. Emphasis and Style − Different fonts convey various tones and styles allowing users to emphasize specific elements or create a particular visual atmosphere.

Setting Font Properties Globally

我们可以使用 plt.rcParams 为整个绘图全局配置字体属性。

We can configure font properties globally for the entire plot using plt.rcParams.

plt.rcParams['font.family'] = 'sans-serif'
plt.rcParams['font.size'] = 12

在即将到来的章节中,我们来分别仔细了解字体的每个参数。

In the upcoming chapters let’s go through the each parameter of the fonts in detail.

以下是 matplotlib 库中常见的字体相关函数。

The following are the common font related functions in matplotlib library.

  1. plt.rcParam − plt.rcParams in Matplotlib is a dictionary-like object that allows you to globally configure various settings that affect the appearance and behavior of plots and figures. It serves as a central configuration system for Matplotlib, providing a convenient way to set default parameters for different elements in visualizations.

  2. Functions to set font properties − We can set the font properties for axis labels and titles using the plt.xlabel(), plt.ylabel() and, plt.title() functions.

  3. Setting font properties to annotations − Similarly, we can set font properties for annotations and text elements using plt.text() and, plt.annotate() functions

Listing All the Available Fonts

要获取 Matplotlib 当前可用的所有字体的列表,我们可以像下面那样使用 font_manager.findSystemFonts() 方法:

To get a list of all the fonts currently available for matplotlib we can use the font_manager.findSystemFonts() method as shown below −

from matplotlib import font_manager
print("List of all fonts currently available in the matplotlib:")
print(*font_manager.findSystemFonts(fontpaths=None, fontext='ttf'), sep="")

上述程序生成以下内容: output -

The above program generates the following output

List of all fonts currently available in the matplotlib:
C:\WINDOWS\Fonts\PERBI___.TTFC:\WINDOWS\Fonts\ARIALUNI.TTFC:\Windows\Fonts\BRLNSR.TTFC:\Windows\Fonts\calibri.ttfC:\WINDOWS\Fonts\BOD_PSTC.TTFC:\WINDOWS\Fonts\WINGDNG3.TTFC:\Windows\Fonts\segoeuisl.ttfC:\Windows\Fonts\HATTEN.TTFC:\WINDOWS\Fonts\segoepr.ttfC:\Windows\Fonts\TCCM____.TTFC:\Windows\Fonts\BOOKOS.TTFC:\Windows\Fonts\BOD_B.TTFC:\WINDOWS\Fonts\corbelli.ttfC:\WINDOWS\Fonts\TEMPSITC.TTFC:\WINDOWS\Fonts\arial.ttfC:\WINDOWS\Fonts\cour.ttfC:\Windows\Fonts\OpenSans-Semibold.ttfC:\WINDOWS\Fonts\palai.ttfC:\Windows\Fonts\ebrimabd.ttfC:\Windows\Fonts\taileb.ttfC:\Windows\Fonts\SCHLBKI.TTFC:\Windows\Fonts\AGENCYR.TTFC:\Windows\Fonts\tahoma.ttfC:\Windows\Fonts\ARLRDBD.TTFC:\WINDOWS\Fonts\corbeli.ttfC:\WINDOWS\Fonts\arialbd.ttfC:\WINDOWS\Fonts\LTYPEBO.TTFC:\WINDOWS\Fonts\LTYPEB.TTFC:\WINDOWS\Fonts\BELLI.TTFC:\WINDOWS\Fonts\YuGothR.ttcC:\WINDOWS\Fonts\OpenSans-Semibold.ttfC:\Windows\Fonts\trebucbd.ttfC:\WINDOWS\Fonts\OCRAEXT.TTFC:\WINDOWS\Fonts\JUICE___.TTFC:\WINDOWS\Fonts\comic.ttfC:\Windows\Fonts\VIVALDII.TTFC:\Windows\Fonts\Candarali.ttfC:\WINDOWS\Fonts\comici.ttfC:\WINDOWS\Fonts\RAVIE.TTFC:\WINDOWS\Fonts\LeelUIsl.ttfC:\Windows\Fonts\ARIALNB.TTFC:\WINDOWS\Fonts\LSANSDI.TTFC:\Windows\Fonts\seguibl.ttfC:\WINDOWS\Fonts\himalaya.ttfC:\WINDOWS\Fonts\TCBI___
..................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................
TTFC:\Windows\Fonts\BOD_BLAR.TTFC:\WINDOWS\Fonts\ebrima.ttfC:\Windows\Fonts\LTYPEB.TTFC:\WINDOWS\Fonts\FRABKIT.TTFC:\WINDOWS\Fonts\REFSAN.TTFC:\WINDOWS\Fonts\gadugi.ttfC:\Windows\Fonts\times.ttfC:\WINDOWS\Fonts\MTCORSVA.TTFC:\WINDOWS\Fonts\ERASDEMI.TTFC:\Windows\Fonts\himalaya.ttfC:\WINDOWS\Fonts\georgiai.ttf

Listing all the font families (or Name of Fonts)

在这里,通过使用以下代码,我们将获得字体系列的列表,即字体名称。

Here by using the below code we will get the list of the font family i.e. Name of fonts.

from matplotlib import font_manager
print("List of all fonts currently available in the matplotlib:")
print(*font_manager.findSystemFonts(fontpaths=None, fontext='ttf'), sep="")

上述程序生成以下内容: output -

The above program generates the following output

List of all fonts currently available in the matplotlib:
cmsy10
STIXGeneral
STIXSizeThreeSym
DejaVu Sans Mono
STIXGeneral
STIXSizeOneSym
.......................................................................
ITC Bookman
Computer Modern
Times
Palatino
New Century Schoolbook

Controlling Font Properties

Font Size (fontsize)

使用函数中的 fontsize 参数(例如 plt.xlabel(), plt.ylabel(), plt.title() 等)设置文本元素的大小。

Set the size of text elements using the fontsize parameter in functions like plt.xlabel(), plt.ylabel(), plt.title() etc.

在这个示例中,我们通过将 fontsize 参数传递给 plt.xlabel(), plt.ylabel()plt.title() 函数来设置文本的大小。

In this example we are setting the size of the text by passing the fontsize parameter to the plt.xlabel(), plt.ylabel() and plt.title() functions.

import matplotlib.pyplot as plt
# Creating a data
x = [i for i in range(10,40)]
y = [i for i in range(30,60)]

# Creating a plot
plt.scatter(x,y,color = 'blue')
plt.xlabel('X-axis cube values', fontsize = 10)
plt.ylabel('Y-axis cube values', fontsize = 12)
plt.title('plot with defined font size')
plt.show()
font size

Font Style (fontstyle)

我们可以为要在创建的绘图上使用的字体选择“普通”、“斜体”或“倾斜”等字体样式。

We can choose the font styles such as 'normal', 'italic', or 'oblique' for the font that we want to use on the created plot.

在这里,我们通过将 fontstyle 参数传递为 'normal'`, 'italic','oblique'plt.xlabel(), plt.ylabel()plt.title() ,设置我们在绘图上显示的字体的字体样式。

Here we are setting the font style of the fonts that we are displaying on the plot by passing fontstyle parameter as 'normal'`, 'italic', or 'oblique' to the plt.xlabel(), plt.ylabel() and plt.title().

import matplotlib.pyplot as plt
# Creating a data
x = [i for i in range(10,40)]
y = [i for i in range(30,60)]

# Creating a plot
plt.scatter(x,y,color = 'blue')
plt.xlabel('X-axis cube values', fontsize = 10)
plt.ylabel('Y-axis cube values', fontsize = 12)
plt.title('plot with defined font size')
plt.show()
defined font size

Font Weight (fontweight)

使用权重(如 'normal', 'bold',numerical )或 400, 700 等值调整字体的粗细。

Adjust the thickness of the font using weights like 'normal', 'bold', or numerical values such as 400, 700, etc.

import matplotlib.pyplot as plt
# Creating a data
x = [i for i in range(10,40)]
y = [i for i in range(30,60)]

# Creating a plot
plt.scatter(x,y,color = 'blue')
plt.xlabel('X-axis cube values', fontweight='bold')
plt.ylabel('Y-axis cube values', fontweight='bold')
plt.title('plot with defined font size',fontweight='bold')
plt.show()
font weight

Changing Font Family

我们可以在 Matplotlib 库中修改各种文本元素的字体系列。下面提到了一些可用的字体系列。

We can modify the font family for various text elements in Matplotlib library. Some available font families are mentioned below.

  1. 'serif' − Serif fonts such as Times New Roman

  2. 'sans-serif' − Sans-serif fonts such as Arial

  3. 'monospace' − Monospaced fonts such as Courier New

Change size of the fonts

我们可以使用 plt.text() 函数来修改字体的大小。

We can change the size of the font by using the plt.text() function.

import matplotlib.pyplot as plt
plt.plot([1, 2, 4], [1, 2, 4])
plt.text(2, 3, "y=x", color='red', fontsize=20)

# Increase fontsize by increasing value.
plt.show()
text size

Embed fonts in PDFs produced by Matplotlib

为了将字体嵌入至由 Matplotlib 生成的 PDF,我们可以使用 rc.Params['pdf.fonttype']=42。

To embed fonts in PDFs produced by Matplotlib we can use rc.Params['pdf.fonttype']=42.

import numpy as np
from matplotlib import pyplot as plt, font_manager as fm

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
plt.rcParams['pdf.fonttype'] = 42

fig, ax = plt.subplots()
x = np.random.rand(100)
y = np.random.rand(100)

ax.scatter(x, y, c=y, marker="v")

fprop = fm.FontProperties(fname='C:\Windows\Fonts\MISTRAL.TTF')

ax.set_title('Scatter Plot With Random Points',
   fontproperties=fprop, size=20, fontweight="bold")

plt.savefig("demo.pdf")

当我们执行代码时,它将以 "demo.pdf" 为文件名将以下图片保存至项目目录中。

When we execute the code it will save the following plot in the project directory with the file name as "demo.pdf".

font pdf

Setting Font Properties Globally

在 Matplotlib 库中全局设置字体属性涉及使用 plt.rcParams 方法配置整个绘图的默认字体设置。当我们希望对可视化效果中的所有文本元素应用一致的字体样式、大小或系列而无需为每个组件单独指定它们时,这一点非常有用。

Setting font properties globally in Matplotlib library involves configuring default font settings for the entire plot using plt.rcParams method. This is useful when we want to apply consistent font styles, sizes or families to all text elements in our visualizations without specifying them individually for each component.

值得注意的是,我们可以根据自己的偏好和我们希望在绘图中实现的视觉样式来定制这些设置。我们可以调整值以匹配我们期望的字体样式、大小和系列,以便在我们的可视化效果中获得一致且美观的展示效果。

It’s important to note that we can tailor these settings based on our preferences and the visual style we want to achieve in our plots. We can adjust the values to match our desired font styles, sizes and families for a consistent and aesthetically pleasing appearance across our visualizations.

以下是我们可用 plt.rcParams 方法进行的不同设置。

The following are the different settings that we can make by using the plt.rcParams method.

plt.rcParams['font.family'] = font_name

这为文本元素(如 'sans-serif' )设置默认字体系列。我们可以用 'serif', 'monospace' 等可用字体系列或特定字体名称替换 font_name。

This sets the default font family for text elements such as 'sans-serif'. We can replace font_name with the available font families such as 'serif', 'monospace' or specific font names.

Example

在这个示例中,我们尝试将字体系列设置成 'sans-serif' 和使用 plt.rcParams['font.family']

In this example we are trying to set the font family to 'sans-serif' by using the plt.rcParams['font.family'].

import matplotlib.pyplot as plt
# Set font properties globally
plt.rcParams['font.family'] = 'sans-serif'

# Create a plot
plt.plot([1, 2, 3], [4, 5, 6])
plt.xlabel('X-axis Label')
plt.ylabel('Y-axis Label')
plt.title('Font Family setting')
plt.show()
font family

plt.rcParams['font.size'] = font_size

我们可以根据需求将数值值指定为文本元素的默认字体大小。这样可以确保所有文本元素都使用该字体大小,而不会因某些组件而出错。

We can specify the default font size for text elements in numerical values as per the requirement. This ensures that all text elements use this font size unless overridden for specific components.

Example

在此示例中,我们将字体大小指定为 8 点,向 plt.rcParams['font.size'] 显示整个图表的字体大小。

In this example we are specifying the fontsize as 8 points to the plt.rcParams['font.size'] to display font size globally all over the plot.

import matplotlib.pyplot as plt
# Set font properties globally
plt.rcParams['font.size'] = 8

# Create a plot
plt.plot([1, 2, 3], [4, 5, 6])
plt.xlabel('X-axis Label')
plt.ylabel('Y-axis Label')
plt.title('Font Size setting')
plt.show()
font size setting

plt.rcParams['font.style'] = 'fontstyle'

我们可以定义字体样式,例如倾斜等,由我们对 plt.rcParams['font.style'] 的兴趣而定。这会针对图表中的文本元素应用已定义的外观。

We can define the font style such as italic etc., as per our interest to the plt.rcParams['font.style']. This applies the defined appearance to text elements throughout the plot.

Example

在此示例中,我们将字体样式指定为 italicplt.rcParams['font.style']

In this example we are specifying the font style as italic to the plt.rcParams['font.style'].

import matplotlib.pyplot as plt
# Set font properties globally
plt.rcParams['font.style'] = 'italic'

# Create a plot
plt.plot([1, 2, 3], [4, 5, 6])
plt.xlabel('X-axis Label')
plt.ylabel('Y-axis Label')
plt.title('Font Style setting')
plt.show()
font style

plt.rcParams['font.weight'] = font_weight

通过此方法,我们可以设置字体粗细,例如“粗体”等,从而根据用户要求显示文本元素中的字符,并为其指定样式。

By using this we can set the font weight such as 'bold' etc. This makes the characters in text elements appear in the defined style as per the user requirement.

Example

在此示例中,我们将字体粗细指定为 plt.rcParams['font.weight'] 的粗体。

Here in this example we are specifying the font weight as bold to the plt.rcParams['font.weight'].

import matplotlib.pyplot as plt
# Set font properties globally
plt.rcParams['font.weight'] = 'bold'

# Create a plot
plt.plot([1, 2, 3], [4, 5, 6])
plt.xlabel('X-axis Label')
plt.ylabel('Y-axis Label')
plt.title('Font weight setting')
plt.show()
font weight setting

Note − 通过使用 plt.rcParams 在全局设置这些参数,我们可以确保将这些默认字体特性应用到 Matplotlib 图表中的所有文本元素。当创建标签、标题或其他文本组件时,这些组件将继承这些全局设置,除非我们针对本地指定不同的特性。

Note − By setting these parameters globally using plt.rcParams we can ensure that these default font properties are applied to all text elements in our Matplotlib plots. When we create labels, titles or other text components they will inherit these global settings unless we specify different properties locally.

Change the font properties of a Matplotlib colorbar label

此示例中,我们更改 matplotlib 色条标签的字体属性。

In this example we are changing the font properties of a matplotlib colorbar label.

Example

import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
x, y = np.mgrid[-1:1:100j, -1:1:100j]
z = (x + y) * np.exp(-5.0 * (x ** 2 + y ** 2))
plt.imshow(z, extent=[-1, 1, -1, 1])
cb = plt.colorbar(label='my color bar label')
plt.show()
color bar font

Setting the size of the plotting canvas

在此示例中,我们在 matplotlib 中设置绘图画布的大小。

Here in this example we are setting the size of the plotting canvas in matplotlib.

Example

import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.linspace(-2, 2, 100)
y = np.sin(x)
plt.plot(x, y)
plt.show()
canvas

Auto adjust font size in Seaborn heatmap using Matplotlib

我们通过 Matplotlib 库自动调整 seaborn 热图的字体大小。

Here we are auto adjusting the font size in seaborn heatmap by using the Matplotlib library.

Example

import numpy as np
import seaborn as sns
from matplotlib import pyplot as plt
import pandas as pd
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
d = {
   'y=1/x': [1 / i for i in range(1, 10)],
   'y=x': [i for i in range(1, 10)],
   'y=x^2': [i * i for i in range(1, 10)],
   'y=x^3': [i * i * i for i in range(1, 10)]
}
df = pd.DataFrame(d)
ax = sns.heatmap(df, vmax=1)
plt.xlabel('Mathematical Expression', fontsize=16)
plt.show()
seaborn heatmap

Set the font size of Matplotlib axis Legend

在此示例中,我们设置 matplotlib 坐标轴图例的字体大小。

In this example we are setting the font size of matplotlib axis legend

Example

import numpy as np
from matplotlib import pyplot as plt
import matplotlib
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.linspace(1, 10, 50)
y = np.sin(x)
plt.plot(x, y, c="red", lw=7, label="y=sin(x)")
plt.title("Sine Curve")
matplotlib.rcParams['legend.fontsize'] = 20
plt.legend(loc=1)
plt.show()
legend size

Modify the font size in Matplotlib-venn

要处理 Matplotlib-venn,我们首先需要使用以下代码安装软件包。如果已安装,我们可以直接导入。

To work with the Matplotlib-venn, first we have to install the package by using the below code. If previously installed we can import directly.

pip install matplotlib-venn

Example

在此示例中,我们通过使用 set_fontsize() 方法修改 Matplotlib-venn 中的字体大小。

In this example we are modifying the font size in Matplotlib-venn by using the set_fontsize() method.

from matplotlib import pyplot as plt
from matplotlib_venn import venn3
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
set1 = {'a', 'b', 'c', 'd'}
set2 = {'a', 'b', 'e'}
set3 = {'a', 'd', 'f'}
out = venn3([set1, set2, set3], ('Set1', 'Set2', 'Set3'))
for text in out.set_labels:
   text.set_fontsize(25)
for text in out.subset_labels:
   text.set_fontsize(12)
plt.show()
venn

Change xticks font size

要更改 matplotlib 图表中 x 坐标刻度的字体大小,我们可以使用 fontsize 参数。

To change the font size of xticks in a matplotlib plot we can use the fontsize parameter.

Example

from matplotlib import pyplot as plt
import numpy as np

# Set the figure size
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

# x and y data points
x = np.linspace(-5, 5, 100)
y = np.sin(x)
plt.plot(x, y)

# Set the font size of xticks
plt.xticks(fontsize=25)

# Display the plot
plt.show()
xticks size