当辅助 x 轴 uselatex = true 时,Matplotlib 不使用一致的字体

问题描述 投票:0回答:1

以下 MWE:

import matplotlib

matplotlib.use('TkAgg')
import matplotlib.pyplot as plt

# Use latex
import os
os.environ["PATH"] += os.pathsep + '/usr/local/texlive/2024/bin/x86_64-linux'

if __name__ == '__main__':
    test_data = 10
    test_data_2 = 24

    # Create plot and axis
    fig, ax = plt.subplots()

    plt.rcParams.update({
    "text.usetex": True,
    "font.family": "serif",
    "font.serif": "Computer Modern Roman",
    })

    # Plot
    ax.plot([i for i in range(test_data)], [i for i in range(test_data)], label="Test")
    ax.tick_params(bottom=False)

    # Define x axis
    x_axis = ['30', '40', '50'] * (test_data_2 // 3)
    ax.set_xticks(range(len(x_axis)), labels=(x_axis))

    # Add second x axis
    sec2 = ax.secondary_xaxis(location=0)
    sec2.set_xticks([5.5 + 12 * i for i in range(test_data_2 // 12)],
                    labels=[f'\n\n\n{5 + i * 5}' for i in range(test_data_2 // 12)])
    sec2.tick_params('x', length=0)

    plt.show()

产生以下情节:

enter image description here

可以看到,只有 5 和 10 的辅助 x 轴与第一个轴的字体不同。

我尝试使用 ax.set_xticklabels 或 sec2.set_... 来单独设置标签,但这产生了相同的结果。此外,进一步格式化文本(例如添加 $$ 或 $ rac{..}$)会产生相同的字体差异。

我想要统一的字体,并且希望次要 x 轴使用与主要 x 轴相同的字体。

我怎样才能实现这个目标?

python matplotlib plot
1个回答
0
投票

您将在创建图形和主轴对象之后、创建辅助轴之前设置字体系列并打开

uselatex

如果您希望所有内容都使用 LaTeX 和衬线字体,则只需在创建图形之前设置相关的

rcParams
即可。

即将

fig, ax = plt.subplots()
移至
plt.rcParams.update(...)
之后。

您确实说过您希望所有内容都使用主轴上当前使用的字体。如果是这种情况,您只需删除此处的

rcParams
,所有内容都将具有主轴的字体。但这样你就不会使用 LaTeX,所以这可能不是你真正想要的。

© www.soinside.com 2019 - 2024. All rights reserved.