Matplotlib 简明教程
Matplotlib - 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()
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()
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
在此示例中,我们将字体样式指定为 italic 和 plt.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()
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()
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()
Setting the size of the plotting canvas
在此示例中,我们在 matplotlib 中设置绘图画布的大小。
Here in this example we are setting the size of the plotting canvas in matplotlib.
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()
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()
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()
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()