python - Matplotlib:设置上标字体大小

标签 python matplotlib

在 Matplotlib 中,如何设置上标的字体大小(除了控制底的字体大小)? 例如,使用 Matplotlib 创建一个带有科学记数法坐标轴的图形:设置刻度标签的字体大小很容易,但是如何指定它们的指数的字体大小? 我想对基数和指数进行不同的控制(即,播放刻度标签的字体大小以获得所需大小的指数不是一个好的选择 - 我们可以修改字体大小的比例吗基数和指数?)。 谢谢。

最佳答案

如果你有指数,基本上有两种可能性你已经获得了文本:

  1. 通过使用外部 TeX 安装(在这种情况下,您有 rcParams['text.usetex'] == True)。
  2. 通过使用 matplotlib 中内置的 mathtext Tex 克隆

如果您使用的是外部 TeX 安装,则由 TeX 决定(我的猜测是类似于 \DeclareMathSizes{10}{18}{12}{8},但我没有试过了)。

如果您使用的是“标准”方法,则字体大小比率将硬编码到 matplotlib 中。所以,没有办法改变它们;根据 Donald Knuth 的原始 TeX 规范,上标占基本字体的 70%。


在说“没办法”之后,我会展示一个方法。但这不是一条美丽的道路......

由于 matplotlib 主要是用 Python 编写的,您可能会更改很多东西。您需要的参数在文件 .../matplotlib/mathtext.py 中。 ... 取决于您的 Python 发行版和操作系统。 (比如我的是/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/mathtext.py)

在该文件中,第 1200 行应该是这样的:

# How much text shrinks when going to the next-smallest level.  GROW_FACTOR
# must be the inverse of SHRINK_FACTOR.
SHRINK_FACTOR   = 0.7
GROW_FACTOR     = 1.0 / SHRINK_FACTOR
# The number of different sizes of chars to use, beyond which they will not
# get any smaller
NUM_SIZE_LEVELS = 6
# Percentage of x-height of additional horiz. space after sub/superscripts
SCRIPT_SPACE    = 0.2
# Percentage of x-height that sub/superscripts drop below the baseline
SUBDROP         = 0.3
# Percentage of x-height that superscripts drop below the baseline
SUP1            = 0.5
# Percentage of x-height that subscripts drop below the baseline
SUB1            = 0.0
# Percentage of x-height that superscripts are offset relative to the subscript
DELTA           = 0.18

您可以更改这些以使文本间距不同。例如,让我们制作一个简单的测试图:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0,5, 1000)
y = np.sin(x**2)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y)
ax.set_xlabel(r'$x_1$')
ax.set_ylabel(r'$sin(x_1^2)$')
ax.text(.5, -.5, r'$\rm{this\ is}_\mathrm{subscript}$', fontsize=24)
ax.text(.5, -.7, r'$\rm{this\ is}^\mathrm{superscript}$', fontsize=24)
ax.text(.5, -.9, r'$\frac{2}{1+\frac{1}{3}}$', fontsize=24)

这给出:

enter image description here

然后我们做一些魔术:

import matplotlib

matplotlib.mathtext.SHRINK_FACTOR = 0.5
matplotlib.mathtext.GROW_FACTOR = 1 / 0.5

然后再次运行相同的绘图代码:

enter image description here

如您所见,上标/下标大小发生了变化。但不幸的是它有副作用,如果你看一下分数。

关于python - Matplotlib:设置上标字体大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24684897/

相关文章:

python-2.7 - 使用带有关键字旋转 ='vertical' 的 networkx draw_networkx_labels 不会旋转标签文本

带有带括号的 header 的 Python DataFrame 错误

python - 如何为使用 matplotlib 创建的 PDF 文档创建标题页

python - 理解元组计算

python - skimage.io.imsave "destroys"灰度图像?

python - 如何删除 Pandas 中不以 'x' 开头的行或保留以 'x' 开头的行

python - Tensorflow 向量的形状为 (col,)

python - 在图中容纳参数值的最佳方式

python - 在 ubuntu 13.04 中安装 py2cairo-1.10.0

python - 在 Python 中是否有更简洁的方法来编写此 bool 比较?