为什么siunitx LaTeX包会向matplotlib图中的某些文本元素添加垂直偏移?

2024-09-29 23:22:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用LaTeX渲染matplotlib图形中的文本。当我将包siunitx添加到LaTeX前言中时,一些文本元素不再正确地垂直对齐

我最近才遇到这个问题:以前正确渲染的图形现在已损坏。它会影响多个python环境,所以我认为这可能是由于siunitx的最新版本

以下是我的最低工作示例:

import numpy as np
import matplotlib.pyplot as plt

# Test data
x = np.linspace(0, 2*np.pi, 64)
y = np.sin(x)

# Use latex for text
plt.rcdefaults()
plt.rcParams['text.usetex'] = True

# Correctly behaving text
fig0, ax0 = plt.subplots()
ax0.plot(x, y, label='some string')
ax0.legend()
fig0.tight_layout()
fig0.savefig('without_siunitx.png')
plt.show()

# Use siunitx
plt.rcParams['text.latex.preamble'] = '\n'.join([
    r'\usepackage{siunitx}',
])

# Now some text has incorrect y position
fig1, ax1 = plt.subplots()
ax1.plot(x, y, label='some string')
ax1.legend()
fig1.tight_layout()
fig1.savefig('with_siunitx.png')
plt.show()

作为最简单的工作示例,我在Windows 10上使用python 3.8.12、matplotlib 3.3.2和siunitx 3.0.32(通过MiKTeX安装)

生成的两个png图像链接如下:

Correctly aligned figure without siunitx

Incorrectly aligned figure with siunitx

可以看到,使用siunitx后,图例文本和y轴刻度标签未对齐

我真的很感谢任何能帮助我解决这个问题的人,因为这影响到我论文的大部分数据。非常感谢


Tags: text文本图形示例pngmatplotlibnpplt

热门问题