设置“ matplotlib.rcParams ['text.usetex'] = True”以在标签中使用LaTeX并使用德语语言环境使用逗号时的Python图形问题

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

我想创建其中x和y刻度标签显示其数字值的格式,这些数字值已正确设置为德语格式,即使用逗号作为小数点分隔符。我也想使用LaTeX元素在x或y轴标签或图例中。以下代码显示第一个图形是根据英语版本创建的。

# -*- coding: utf-8 -*-
import numpy as np
import matplotlib
import matplotlib.pyplot as plt

import locale

#  Set to German locale to get comma decimal separater
locale.setlocale(locale.LC_NUMERIC, "deu_deu")

# Use LaTeX elements
matplotlib.rcParams['text.usetex'] = True

t = np.linspace(0.0, 1.0, 100)
s = t*np.cos(4 * np.pi * t) + 2

fig, ax = plt.subplots(figsize=(6, 4))
ax.plot(t, s)

ax.set_xlabel(r'Time $t$ with $t \le 1$')
ax.set_ylabel('Velocity $v(t)$')

plt.show()

fig.savefig("Mein_Test1.pdf")


fig2, ax2 = plt.subplots(figsize=(6, 4))
ax2.plot(t, s)

ax2.set_xlabel(r'Time $t$ with $t \le 1$')
ax2.set_ylabel('Velocity $v(t)$')

plt.ticklabel_format(useLocale=True)

plt.show()

fig2.savefig("Mein_Test2.pdf")

The first figure looks as desired, with nice English points as decimal separators and nice spacing in the axis tick labels, and I can use the LaTeX "\le" symbol in the x axix label:

However, the second figure shows an ugly spacing in the numbers of axis tick labels, with too much space behind the decimal separator:

如果我这样做[[not使用“ matplotlib.rcParams ['text.usetex'] = True”,那么我不能在标签中包含LaTeX元素,即,没有” \ le“符号,但是要有空格即使对于德国逗号也是正确的。因此,德语语言环境与“ text.usetex”之间似乎存在一些冲突。任何想法都正确吗?谢谢!

python matplotlib latex locale
1个回答
0
投票
[我最终找到了一种方法,也可以使用lambda函数通过查看this问题的答案来获得所需的结果。这是代码:

# -*- coding: utf-8 -*- import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import locale # Set to German locale to get comma decimal separater locale.setlocale(locale.LC_NUMERIC, "deu_deu") # Use LaTeX elements mpl.rcParams['text.usetex'] = True t = np.linspace(0.0, 1.0, 100) s = t*np.cos(4 * np.pi * t) + 2 fig2, ax2 = plt.subplots(figsize=(6, 4)) ax2.ticklabel_format(useLocale=True) ax2.plot(t, s) ax2.set_xlabel(r'Time $t$ with $t \le 1$') ax2.set_ylabel('Velocity $v(t)$') plt.ticklabel_format(useLocale=True) ax2.get_yaxis().set_major_formatter(mpl.ticker.FuncFormatter(lambda x, loc: locale.format_string('%1.3f', x, 1))) ax2.get_xaxis().set_major_formatter(mpl.ticker.FuncFormatter(lambda x, loc: locale.format_string('%0.2f', x, 2))) plt.show() fig2.savefig("Mein_Test2.png")

现在我得到了desired result:
© www.soinside.com 2019 - 2024. All rights reserved.