如何在matplotlib中调整百分比格式轴的刻度标签字体?

gblwokeq  于 2023-03-09  发布在  其他
关注(0)|答案(1)|浏览(133)

我通常将matplotlib与以下选项一起使用:

matplotlib.rcParams['text.latex.preamble'] = r'\usepackage{amsmath}'
matplotlib.rc('text', usetex = True)

这样文本字体看起来更好(至少对我来说)。但是,如果我将其中一个轴的格式设置为百分比,则该轴上刻度标签的字体将恢复为默认值。以下是一个MWE:

import numpy as np

import matplotlib
matplotlib.use('Agg')
matplotlib.rcParams['text.latex.preamble'] = r'\usepackage{amsmath}'
matplotlib.rc('text', usetex = True)
from matplotlib import pyplot as py

## setup figure
figure = py.figure(figsize = (7.5, 5.0))
axs = [py.subplot(1, 1, 1)]

## make plot
xs = np.linspace(0.0, np.pi, 100)
ys = np.sin(xs)
axs[0].plot(xs, ys, color = 'dodgerblue', label = r'$n = 1$')
ys = np.sin(2.0 * xs)
axs[0].plot(xs, ys, color = 'seagreen', label = r'$n = 2$')
axs[0].axhline(0.0, color = 'gray', linestyle = 'dashed')

## percentage y axis
formatter = matplotlib.ticker.PercentFormatter(xmax = 1.0, decimals = 0, symbol = r'\%', is_latex = True)
axs[0].yaxis.set_major_formatter(formatter)

## save figure
name = 'test.pdf'
py.tight_layout()
py.savefig(name)
py.close()

如下图所示,纵轴和横轴的字体不一样,如何设置为与横轴的字体相同?谢谢!

enxuqcxy

enxuqcxy1#

我找到了一个变通办法,它并不完美,但它解决了问题:

import numpy as np

import matplotlib
matplotlib.use('Agg')
matplotlib.rcParams['text.latex.preamble'] = r'\usepackage{amsmath}'
matplotlib.rc('text', usetex = True)
from matplotlib import pyplot as py

## setup figure
figure = py.figure(figsize = (7.5, 5.0))
axs = [py.subplot(1, 1, 1)]

## make plot
xs = np.linspace(0.0, np.pi, 100)
ys = np.sin(xs)
axs[0].plot(xs, ys, color = 'dodgerblue', label = r'$n = 1$')
ys = np.sin(2.0 * xs)
axs[0].plot(xs, ys, color = 'seagreen', label = r'$n = 2$')
axs[0].axhline(0.0, color = 'gray', linestyle = 'dashed')

## percentage y axis
y_low, y_up = axs[0].get_ylim()
y_ticks = [_ for _ in axs[0].get_yticks() if (_ > y_low) and (_ < y_up)]
y_labels = [r'${:g}\%$'.format(_ * 100.0) for _ in y_ticks]
axs[0].set_yticks(y_ticks)
axs[0].set_yticklabels(y_labels)
## ^ ^ ^ ^ ^ ^ ^ see this part ^ ^ ^ ^ ^ ^ ^

## save figure
name = 'test.pdf'
py.tight_layout()
py.savefig(name)
py.close()

因此,我现在不使用matplotlib.ticker.PercentFormatter,而是手动定义刻度标签。

相关问题