You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Matplotlib绘图中使用LaTeX默认字体并添加四侧刻度短划线

问题:调整Matplotlib图表字体与网格样式

我在Jupyter中使用以下代码生成图表:

import numpy as np
import matplotlib.pyplot as plt
import sympy as sp
from scipy.integrate import quad
import math
from matplotlib.patches import Circle

fig2 = plt.figure(figsize=(10,8))
plt.subplot(1, 1, 1)
plt.plot(2, 5, marker='*', markersize=25, color='gold')
plt.plot(2, -5, marker='*', markersize=25, color='gold')
plt.plot(3, 0, marker='*', markersize=25, color='gold')
plt.xlabel(r"$x [rg]$", fontsize=20)
plt.ylabel(r"$y [rg]$", fontsize=20)
circle = Circle((0, 0), 1, color='black')
plt.gca().add_patch(circle)
plt.gca().set_aspect('equal')
plt.axis([-10, 30, -10, 10])
plt.tick_params(axis='both', labelsize=20)

当前生成的图表样式如图所示,我希望让图表的文本和数字均使用LaTeX默认字体,同时在绘图四侧添加短划线网格,使其接近目标样式,请问该如何实现?


解决方案

可以通过以下修改实现需求,完整代码如下:

import numpy as np
import matplotlib.pyplot as plt
import sympy as sp
from scipy.integrate import quad
import math
from matplotlib.patches import Circle

# 配置Matplotlib使用LaTeX默认字体
plt.rcParams.update({
    "text.usetex": True,
    "font.family": "serif",
    "font.serif": ["Computer Modern Roman"],
})

fig2 = plt.figure(figsize=(10,8))
ax = plt.subplot(1, 1, 1)
plt.plot(2, 5, marker='*', markersize=25, color='gold')
plt.plot(2, -5, marker='*', markersize=25, color='gold')
plt.plot(3, 0, marker='*', markersize=25, color='gold')
plt.xlabel(r"$x [rg]$", fontsize=20)
plt.ylabel(r"$y [rg]$", fontsize=20)
circle = Circle((0, 0), 1, color='black')
ax.add_patch(circle)
ax.set_aspect('equal')
plt.axis([-10, 30, -10, 10])
plt.tick_params(axis='both', labelsize=20)

# 添加短划线网格并显示四侧边框
ax.grid(True, linestyle='--', linewidth=0.8)
ax.spines[['top', 'right', 'bottom', 'left']].set_visible(True)

关键修改说明:

  • 启用LaTeX字体:通过plt.rcParams.update配置,开启text.usetex并指定LaTeX默认的Computer Modern Roman字体,确保所有文本(包括坐标轴刻度数字、标签)都使用LaTeX样式。
  • 添加短划线网格:调用ax.grid(True, linestyle='--', linewidth=0.8)生成短划线网格,可根据需要调整linewidth控制网格线粗细。
  • 保留四侧边框:通过ax.spines[['top', 'right', 'bottom', 'left']].set_visible(True)确保绘图区域四侧边框都显示,与目标样式一致。

内容的提问来源于stack exchange,提问作者Projetos Programação

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 09:13:10