【发布时间】:2014-07-11 13:47:28
【问题描述】:
在 Matplotlib 中,如何设置上标的字体大小(除了控制基的字体大小)? 例如,使用 Matplotlib 创建一个带有科学记数法轴的图形:设置刻度标签的字体大小很容易,但如何指定其指数的字体大小? 我想对基数和指数进行差分控制(即,在刻度标签的字体大小上播放以获得所需大小的指数不是一个好的选择 - 我们可以修改字体大小的比率吗?基数和指数?)。 谢谢。
【问题讨论】:
标签: python matplotlib
在 Matplotlib 中,如何设置上标的字体大小(除了控制基的字体大小)? 例如,使用 Matplotlib 创建一个带有科学记数法轴的图形:设置刻度标签的字体大小很容易,但如何指定其指数的字体大小? 我想对基数和指数进行差分控制(即,在刻度标签的字体大小上播放以获得所需大小的指数不是一个好的选择 - 我们可以修改字体大小的比率吗?基数和指数?)。 谢谢。
【问题讨论】:
标签: python matplotlib
如果你有指数,基本上有两种可能你得到了文本:
rcParams['text.usetex'] == True)。mathtext 内置于matplotlib 中的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)
这给出了:
然后我们做一些魔术:
import matplotlib
matplotlib.mathtext.SHRINK_FACTOR = 0.5
matplotlib.mathtext.GROW_FACTOR = 1 / 0.5
然后再次运行相同的绘图代码:
如您所见,上标/下标大小发生了变化。但不幸的是,如果您查看分数,它会产生副作用。
【讨论】: