如何在简单的Matplotlib图表中设置小刻度的字体大小/重量



我试图制作一个简单的绘图,并为记号设置字体的大小和重量,然而,即使在阅读了matplotlib手册之后,我也不清楚这方面的算法是什么。

我在matplotlib 3.3中使用推荐的OOP方法。这是MWE:

import numpy as np
from matplotlib import pyplot as plt
import matplotlib.ticker as ticker
x = np.linspace(0, 10, 1000)
print(x)
y = x**2
z = 1 + 5*x
# Plotting:
fig, ax = plt.subplots()
ax.plot(x, y, color='blue', linewidth=2.0, label="Quadratic")
ax.plot(x, z, color='orange', linestyle='-.', linewidth=1.5, label="Linear")
# Axis limits
ax.set_xlim(0, 10)
ax.set_ylim(0, 100)
# Axis labels
ax.set_xlabel(r"A linear array of $X$ values", fontsize=16)
ax.set_ylabel(r"Some functions $y(x)$", fontsize=16)
# Ticks:
ax.xaxis.set_major_locator(ticker.AutoLocator())
ax.yaxis.set_major_locator(ticker.AutoLocator())
ax.xaxis.set_minor_locator(ticker.AutoMinorLocator())
ax.yaxis.set_minor_locator(ticker.AutoMinorLocator())
ax.xaxis.set_minor_formatter(ticker.ScalarFormatter())
ax.set_title("Some simple plots", loc='left')
ax.legend(frameon=False)
plt.show()

问题:

  • 如何为主刻度和副刻度上的标签指定字体大小(以pt为单位(和字体重量(即粗体(?我找到了一种通过ax.xaxis.set_tick_params(labelsize=12)指定字体大小的方法,但我找不到将字体加粗的方法
  • 我只能通过ax.xaxis.set_tick_params()指定勾号标签的字体参数吗?有没有办法通过格式化程序指定字体参数
  • 我已经安装了monospace字体"Source Code Pro";。如何将此特定字体用于Matplotlib?我可以指定字体的路径吗

我知道我的问题可能是基本的,但我无法澄清刻度标签格式的算法。我将感谢你的帮助!

如何为主刻度和副刻度上的标签指定字体大小(以pt为单位(和字体重量(即粗体(?

如果您只想设置标签大小,那么tick_params更容易使用。要设置字体权重,则可以通过Axis.get_majorticklabels:获得每个刻度标签的Text实例

for tick in ax.xaxis.get_majorticklabels():
tick.set_fontweight('bold')
# similar for minor tick labels by get_minorticklabels

我只能通过ax.xaxis.set_tick_params((为刻度标签指定字体参数吗?有没有办法通过格式化程序指定字体参数?

如上所述,如果不涉及字体权重,tick_params是更好的选择。据我所知,Formatter与字体属性无关,而是与刻度标签的数字表示有关。所以我不认为字体属性可以通过Formatter指定。

我已经安装了monospace字体"Source Code Pro";。如何将此特定字体用于Matplotlib?我可以指定字体的路径吗?

问题可以转换为how to specify the font name in matplotlib。右键单击字体文件时,可以在属性中找到字体名称。或者,可以使用Text实例的set_fontproperties方法按文件路径设置字体,例如:

for tick in ax.xaxis.get_majorticklabels():
tick.set_fontweight('bold')
tick.set_fontproperties(pathlib.WindowsPath(r'C:UsersDownloadsTTF-source-code-pro-2.038R-ro-1.058R-itSourceCodePro-Regular.ttf'))

最新更新