使用Matplotlib實現(xiàn)自定義坐標(biāo)軸字體及刻度樣式詳解
引言
在數(shù)據(jù)可視化中,坐標(biāo)軸標(biāo)簽和刻度標(biāo)簽的呈現(xiàn)方式直接影響圖表的可讀性和美觀性。Matplotlib 作為 Python 中最流行的繪圖庫,提供了豐富的接口來自定義坐標(biāo)軸的視覺樣式。本文將詳細(xì)介紹如何設(shè)置坐標(biāo)軸標(biāo)題的字體樣式、如何正確顯示負(fù)號,以及如何自定義坐標(biāo)軸刻度標(biāo)簽的多種方法。每個示例代碼塊都是獨立的,讀者可以直接復(fù)制運行。
坐標(biāo)軸標(biāo)題字體設(shè)置
Matplotlib 中設(shè)置坐標(biāo)軸標(biāo)題字體的方法有多種,每種方法適用于不同的場景。以下是幾種常用的設(shè)置方式。
通過 fontdict 參數(shù)設(shè)置
fontdict 參數(shù)允許我們通過字典來指定字體屬性,包括字體族、大小、粗細(xì)、樣式和顏色等。這種方法提供了最全面的控制。

import matplotlib.pyplot as plt
import numpy as np
# 創(chuàng)建示例數(shù)據(jù)
x = np.linspace(0, 2 * np.pi, 100)
y = np.sin(x)
fig, ax = plt.subplots(figsize=(8, 5))
ax.plot(x, y, linewidth=2)
# 使用fontdict設(shè)置字體屬性
ax.set_xlabel('Time (s)',
fontdict={
'family': 'Times New Roman', # 字體名稱
'size': 16, # 字體大小
'weight': 'bold', # 字體粗細(xì)
'style': 'italic', # 字體樣式
'color': 'darkblue' # 字體顏色
})
ax.set_ylabel('Amplitude',
fontdict={
'family': 'Arial',
'size': 14,
'weight': 'normal',
'color': 'darkred'
})
ax.set_title('Sine Wave: $y = \\sin(x)$', fontsize=18, fontweight='bold')
plt.tight_layout()
plt.show()
通過關(guān)鍵字參數(shù)設(shè)置
對于簡單的字體設(shè)置,可以直接使用關(guān)鍵字參數(shù),代碼更加簡潔直觀。

import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y = np.exp(-x/5) * np.cos(2*x)
fig, ax = plt.subplots(figsize=(8, 5))
ax.plot(x, y, 'r-', linewidth=2)
# 使用關(guān)鍵字參數(shù)設(shè)置字體
ax.set_xlabel('Time (seconds)',
fontsize=14,
fontweight='bold',
fontstyle='normal',
fontfamily='DejaVu Sans',
color='navy')
ax.set_ylabel('Signal Strength',
fontsize=14,
fontweight='semibold',
fontfamily='Helvetica',
color='darkgreen')
ax.set_title('Damped Oscillation',
fontsize=16,
fontweight='bold',
fontfamily='Times New Roman')
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
通過 Text 對象設(shè)置
獲取坐標(biāo)軸標(biāo)簽的 Text 對象后,可以直接修改其屬性。這種方法特別適合在創(chuàng)建標(biāo)簽后需要進(jìn)行動態(tài)調(diào)整的場景。

import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-5, 5, 200)
y = np.exp(-x**2/2) / np.sqrt(2*np.pi)
fig, ax = plt.subplots(figsize=(8, 5))
ax.plot(x, y, 'b-', linewidth=2, alpha=0.7)
# 獲取 Text 對象
xlabel = ax.set_xlabel('$x$ (Input Variable)')
ylabel = ax.set_ylabel('$f(x)$', rotation=0)
# 通過 Text 對象的方法設(shè)置屬性
xlabel.set_fontsize(15)
xlabel.set_fontweight('bold')
xlabel.set_fontfamily('Times New Roman')
xlabel.set_color('darkblue')
xlabel.set_style('italic')
ylabel.set_fontsize(15)
ylabel.set_fontweight('bold')
ylabel.set_fontfamily('Times New Roman')
ylabel.set_color('darkred')
ylabel.set_verticalalignment('center')
ylabel.set_position((0, 0.5)) # 調(diào)整標(biāo)簽位置
ax.set_title('Normal Distribution: $f(x) = \\frac{1}{\\sqrt{2\\pi}} e^{-x^2/2}$',
fontsize=16, fontweight='bold')
plt.grid(True, alpha=0.2, linestyle='--')
plt.tight_layout()
plt.show()
通過 rcParams 全局設(shè)置
當(dāng)需要在整個項目或會話中保持一致的字體樣式時,可以使用 rcParams 進(jìn)行全局設(shè)置。

import matplotlib.pyplot as plt
import matplotlib
import numpy as np
# 配置全局設(shè)置
matplotlib.rcParams.update({
'axes.labelsize': 16,
'axes.labelweight': 'bold',
'axes.labelcolor': 'black',
'axes.titlecolor': 'darkblue',
'axes.titlesize': 18,
'axes.titleweight': 'bold',
'font.family': 'sans-serif',
'font.sans-serif': ['Arial', 'DejaVu Sans', 'Helvetica']
})
# 創(chuàng)建子圖
fig, axes = plt.subplots(2, 2, figsize=(12, 10))
x = np.linspace(0, 4*np.pi, 200)
# 繪制不同的三角函數(shù)
functions = [('sin', np.sin), ('cos', np.cos),
('tan', np.tan), ('sinc', lambda x: np.sin(x)/x)]
for ax, (name, func) in zip(axes.flat, functions):
y = func(x)
ax.plot(x, y, linewidth=2)
ax.set_xlabel('$x$ (radians)')
ax.set_ylabel(f'${name}(x)$')
ax.set_title(f'${name}(x)$ Function')
ax.grid(True, alpha=0.3)
# 對正切函數(shù)設(shè)置顯示范圍,避免極端值
if name == 'tan':
ax.set_ylim(-5, 5)
plt.tight_layout()
plt.show()
# 重置為默認(rèn)設(shè)置
matplotlib.rcParams.update(matplotlib.rcParamsDefault)
正確顯示負(fù)號
在使用某些字體(特別是中文字體)時,負(fù)號可能無法正確顯示。以下是解決此問題的幾種方法。
基本配置
設(shè)置 axes.unicode_minus 為 False 是解決負(fù)號顯示問題的關(guān)鍵。

import matplotlib.pyplot as plt
import numpy as np
# 解決負(fù)號顯示問題的基本配置
plt.rcParams['font.sans-serif'] = ['Arial', 'DejaVu Sans', 'Helvetica']
plt.rcParams['axes.unicode_minus'] = False # 關(guān)鍵設(shè)置
# 創(chuàng)建包含負(fù)值的數(shù)據(jù)
x = np.linspace(-2*np.pi, 2*np.pi, 300)
y1 = np.sin(x)
y2 = np.cos(x)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))
# 第一個子圖:正弦函數(shù)
ax1.plot(x, y1, 'b-', linewidth=2)
ax1.set_xlabel('Angle (radians)')
ax1.set_ylabel('$\\sin(\\theta)$')
ax1.set_title('Sine Function with Negative Domain')
ax1.grid(True, alpha=0.3)
ax1.axhline(y=0, color='black', linewidth=0.5, linestyle='-')
ax1.axvline(x=0, color='black', linewidth=0.5, linestyle='-')
# 第二個子圖:余弦函數(shù)
ax2.plot(x, y2, 'r-', linewidth=2)
ax2.set_xlabel('Angle (radians)')
ax2.set_ylabel('$\\cos(\\theta)$')
ax2.set_title('Cosine Function with Negative Domain')
ax2.grid(True, alpha=0.3)
ax2.axhline(y=0, color='black', linewidth=0.5, linestyle='-')
ax2.axvline(x=0, color='black', linewidth=0.5, linestyle='-')
plt.tight_layout()
plt.show()
包含科學(xué)記數(shù)法的負(fù)值顯示
當(dāng)數(shù)據(jù)范圍很大或很小時,科學(xué)記數(shù)法中的負(fù)號也需要正確顯示。

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import FuncFormatter
# 配置以正確顯示負(fù)號
plt.rcParams['axes.unicode_minus'] = False
plt.rcParams['font.size'] = 12
# 創(chuàng)建包含較大負(fù)值的數(shù)據(jù)
x = np.logspace(-3, 3, 200) # 從 $10^{-3}$ 到 $10^{3}$
y = -np.exp(-x) * np.sin(10*x)
fig, ax = plt.subplots(figsize=(10, 6))
ax.semilogx(x, y, linewidth=2, color='purple')
# 使用科學(xué)記數(shù)法格式化刻度標(biāo)簽
formatter = FuncFormatter(lambda val, pos: f'{val:.1e}')
ax.xaxis.set_major_formatter(formatter)
ax.yaxis.set_major_formatter(formatter)
# 自定義刻度參數(shù)
ax.tick_params(axis='both', which='major', labelsize=11)
ax.tick_params(axis='both', which='minor', labelsize=9)
ax.set_xlabel('Time (s)', fontsize=14, fontweight='bold')
ax.set_ylabel('Amplitude (V)', fontsize=14, fontweight='bold')
ax.set_title('Exponential Decay with Oscillation: $y = -e^{-x}\\sin(10x)$',
fontsize=16, fontweight='bold')
ax.grid(True, alpha=0.3, which='both', linestyle='--')
# 添加包含負(fù)值的文本標(biāo)注
ax.text(0.1, -0.7, 'Minimum Value: $-0.5\\times10^{0}$',
fontsize=12, bbox=dict(boxstyle='round', facecolor='yellow', alpha=0.5))
plt.tight_layout()
plt.show()
坐標(biāo)軸刻度字體設(shè)置
坐標(biāo)軸刻度標(biāo)簽的字體設(shè)置同樣重要,Matplotlib 提供了多種方法來定制刻度標(biāo)簽的外觀。
通過 tick_params 方法設(shè)置
tick_params 方法是最常用的設(shè)置刻度標(biāo)簽樣式的方法,它可以同時設(shè)置多個屬性。
import matplotlib.pyplot as plt
import numpy as np
# 設(shè)置中文字體和負(fù)號顯示
plt.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei', 'DejaVu Sans']
plt.rcParams['axes.unicode_minus'] = False
x = np.linspace(0, 10, 100)
y = np.sin(x)
fig, ax = plt.subplots(figsize=(8, 6))
ax.plot(x, y, linewidth=2)
# 設(shè)置刻度字體
ax.tick_params(axis='both', # 同時設(shè)置 x 和 y 軸
labelsize=12, # 刻度標(biāo)簽大小
labelcolor='darkblue', # 刻度標(biāo)簽顏色
rotation=0) # 刻度標(biāo)簽旋轉(zhuǎn)角度
# 或者分別設(shè)置 x 軸和 y 軸
ax.tick_params(axis='x', labelsize=14, labelcolor='red', rotation=45)
ax.tick_params(axis='y', labelsize=12, labelcolor='green')
ax.set_xlabel('X軸標(biāo)題', fontsize=14)
ax.set_ylabel('Y軸標(biāo)題', fontsize=14)
ax.set_title('刻度字體設(shè)置示例', fontsize=16)
plt.tight_layout()
plt.show()
通過 set_xticklabels 和 set_yticklabels 設(shè)置
這種方法可以更精細(xì)地控制每個刻度標(biāo)簽的屬性,包括使用不同的字體族、樣式等。

import matplotlib.pyplot as plt
import numpy as np
# 創(chuàng)建數(shù)據(jù)
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)
fig, ax = plt.subplots(figsize=(8, 6))
ax.plot(x, y, 'b-', linewidth=2)
# 設(shè)置自定義刻度位置
x_ticks = [0, np.pi/2, np.pi, 3*np.pi/2, 2*np.pi]
x_tick_labels = ['0', r'$\frac{\pi}{2}$', r'$\pi$', r'$\frac{3\pi}{2}$', r'$2\pi$']
y_ticks = [-1, -0.5, 0, 0.5, 1]
# 設(shè)置刻度位置和標(biāo)簽
ax.set_xticks(x_ticks)
ax.set_xticklabels(x_tick_labels,
fontsize=14,
fontfamily='Times New Roman',
fontweight='bold',
color='darkblue')
ax.set_yticks(y_ticks)
ax.set_yticklabels([f'{tick:.1f}' for tick in y_ticks],
fontsize=12,
fontfamily='Arial',
color='darkred')
# 設(shè)置刻度線樣式
ax.tick_params(axis='both',
which='major',
length=10,
width=2,
direction='inout')
# 添加次刻度
from matplotlib.ticker import AutoMinorLocator
ax.xaxis.set_minor_locator(AutoMinorLocator(2))
ax.yaxis.set_minor_locator(AutoMinorLocator(2))
ax.tick_params(axis='both', which='minor', length=5, width=1)
ax.set_xlabel('Angle (radians)', fontsize=14, fontweight='bold')
ax.set_ylabel('sin(angle)', fontsize=14, fontweight='bold')
ax.set_title('Trigonometric Function Curve', fontsize=16, fontweight='bold')
ax.grid(True, alpha=0.3, which='both')
plt.tight_layout()
plt.show()
通過循環(huán)設(shè)置每個刻度標(biāo)簽
對于需要為不同刻度設(shè)置不同樣式的復(fù)雜情況,可以遍歷刻度標(biāo)簽并分別設(shè)置。

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.font_manager import FontProperties
fig, ax = plt.subplots(figsize=(8, 6))
x = np.arange(0, 10, 1)
y = np.random.randn(10)
ax.bar(x, y, color='skyblue', edgecolor='navy')
# 創(chuàng)建字體屬性對象
tick_font = FontProperties(
family='Microsoft YaHei',
size=12,
weight='bold',
style='italic'
)
# 設(shè)置 x 軸刻度字體
for label in ax.get_xticklabels():
label.set_fontproperties(tick_font)
label.set_color('darkblue')
label.set_rotation(45)
label.set_horizontalalignment('right')
# 設(shè)置 y 軸刻度字體
for label in ax.get_yticklabels():
label.set_fontproperties(tick_font)
label.set_color('darkred')
ax.set_xlabel('Category', fontsize=14, fontweight='bold')
ax.set_ylabel('Value', fontsize=14, fontweight='bold')
ax.set_title('Bar Chart with Custom Tick Labels', fontsize=16, fontweight='bold')
plt.tight_layout()
plt.show()
全局設(shè)置刻度字體
通過 rcParams 可以全局設(shè)置所有圖表的刻度字體樣式,確保整個項目中的圖表具有一致的外觀。

import matplotlib.pyplot as plt
import matplotlib
import numpy as np
# 使用 update 方法全局設(shè)置
matplotlib.rcParams.update({
'xtick.labelsize': 12, # x 軸刻度字體大小
'ytick.labelsize': 12, # y 軸刻度字體大小
'xtick.color': 'blue', # x 軸刻度顏色
'ytick.color': 'red', # y 軸刻度顏色
'xtick.direction': 'in', # x 軸刻度方向
'ytick.direction': 'in', # y 軸刻度方向
'xtick.major.size': 8, # x 軸主刻度長度
'ytick.major.size': 8, # y 軸主刻度長度
'xtick.minor.size': 4, # x 軸次刻度長度
'ytick.minor.size': 4, # y 軸次刻度長度
'font.family': 'Arial', # 字體族
'axes.unicode_minus': False
})
# 創(chuàng)建圖表
fig, axes = plt.subplots(2, 2, figsize=(12, 10))
x = np.linspace(0, 2*np.pi, 100)
# 繪制不同的三角函數(shù)
functions = [np.sin, np.cos, np.tan, lambda x: np.sin(x)*np.cos(x)]
titles = ['Sine', 'Cosine', 'Tangent', 'Sine × Cosine']
for ax, func, title in zip(axes.flat, functions, titles):
y = func(x)
ax.plot(x, y, linewidth=2)
ax.set_xlabel('x')
ax.set_ylabel('f(x)')
ax.set_title(title)
ax.grid(True, alpha=0.3)
# 對正切函數(shù)設(shè)置顯示范圍
if title == 'Tangent':
ax.set_ylim(-5, 5)
plt.tight_layout()
plt.show()
# 重置為默認(rèn)設(shè)置
matplotlib.rcParams.update(matplotlib.rcParamsDefault)
綜合示例
以下是一個綜合示例,展示了如何同時設(shè)置坐標(biāo)軸標(biāo)題字體、正確顯示負(fù)號,以及自定義刻度標(biāo)簽。

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import MultipleLocator, AutoMinorLocator
# 全局設(shè)置
plt.rcParams['font.size'] = 12
plt.rcParams['axes.unicode_minus'] = False
plt.rcParams['font.family'] = 'Arial'
# 創(chuàng)建包含負(fù)值的數(shù)據(jù)
x = np.linspace(-10, 10, 400)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.exp(-x**2/10) * np.sin(2*x)
# 創(chuàng)建圖形和子圖
fig, axes = plt.subplots(1, 3, figsize=(18, 6))
# 第一個子圖:正弦函數(shù)
axes[0].plot(x, y1, 'b-', linewidth=2)
axes[0].set_xlabel('x (radians)', fontsize=14, fontweight='bold', fontfamily='Times New Roman')
axes[0].set_ylabel('sin(x)', fontsize=14, fontweight='bold', fontfamily='Times New Roman')
axes[0].set_title('Sine Function: $y = \\sin(x)$', fontsize=16, fontweight='bold')
# 設(shè)置刻度
axes[0].tick_params(axis='both', which='major', labelsize=12, length=8, width=1.5)
axes[0].tick_params(axis='both', which='minor', length=4)
axes[0].xaxis.set_minor_locator(AutoMinorLocator(2))
axes[0].yaxis.set_minor_locator(AutoMinorLocator(2))
axes[0].grid(True, which='both', alpha=0.2, linestyle='--')
# 第二個子圖:余弦函數(shù)
axes[1].plot(x, y2, 'r-', linewidth=2)
axes[1].set_xlabel('x (radians)', fontsize=14, fontweight='bold')
axes[1].set_ylabel('cos(x)', fontsize=14, fontweight='bold')
axes[1].set_title('Cosine Function: $y = \\cos(x)$', fontsize=16, fontweight='bold')
# 設(shè)置刻度
axes[1].tick_params(axis='both', which='major', labelsize=12, length=8, width=1.5, colors='darkred')
axes[1].tick_params(axis='both', which='minor', length=4)
axes[1].xaxis.set_minor_locator(AutoMinorLocator(2))
axes[1].yaxis.set_minor_locator(AutoMinorLocator(2))
axes[1].grid(True, which='both', alpha=0.2, linestyle='--')
# 第三個子圖:阻尼振蕩
axes[2].plot(x, y3, 'g-', linewidth=2)
axes[2].set_xlabel('Time (s)', fontsize=14, fontweight='bold')
axes[2].set_ylabel('Amplitude', fontsize=14, fontweight='bold')
axes[2].set_title('Damped Oscillation: $y = e^{-x^2/10} \\cdot \\sin(2x)$', fontsize=16, fontweight='bold')
# 設(shè)置刻度
axes[2].tick_params(axis='both', which='major', labelsize=12, length=8, width=1.5, rotation=45)
axes[2].tick_params(axis='both', which='minor', length=4)
axes[2].xaxis.set_minor_locator(AutoMinorLocator(2))
axes[2].yaxis.set_minor_locator(AutoMinorLocator(2))
axes[2].grid(True, which='both', alpha=0.2, linestyle='--')
plt.tight_layout()
plt.show()
結(jié)語
Matplotlib 提供了豐富的接口來自定義坐標(biāo)軸標(biāo)題和刻度標(biāo)簽的字體樣式。通過本文介紹的多種方法,讀者可以根據(jù)具體需求選擇最適合的方式來美化圖表。無論是簡單的字體大小調(diào)整,還是復(fù)雜的多字體混合使用,Matplotlib 都能提供靈活的解決方案。正確配置坐標(biāo)軸標(biāo)簽的字體樣式不僅能提升圖表的美觀性,還能增強信息的傳達(dá)效果,是數(shù)據(jù)可視化中不可或缺的一環(huán)。
以上就是使用Matplotlib實現(xiàn)自定義坐標(biāo)軸字體及刻度樣式詳解的詳細(xì)內(nèi)容,更多關(guān)于Matplotlib自定義坐標(biāo)軸字體及刻度的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python3.5 Json與pickle實現(xiàn)數(shù)據(jù)序列化與反序列化操作示例
這篇文章主要介紹了Python3.5 Json與pickle實現(xiàn)數(shù)據(jù)序列化與反序列化操作,結(jié)合實例形式分析了Python3.5使用Json與pickle模塊實現(xiàn)json格式數(shù)據(jù)的序列化及反序列化操作相關(guān)步驟與注意事項,需要的朋友可以參考下2019-04-04

