【问题标题】:Matplotlib: Change the fontsize "midway" in textMatplotlib:在文本中更改字体大小“中途”
【发布时间】:2022-01-15 19:06:08
【问题描述】:

我知道this question,它讨论了如何“全局”更改 matplotlib 中的字体大小。我的用例略有不同:我希望输出类似于

数组1 (元素数:100)

数组1 (元素数:250)

所以 MWE 应该是:

import numpy as np
from matplotlib import pyplot as plt

a = np.random.rand(100)
b = np.random.rand(250)
plt.hist(a, bins=100, label='Array 1 (number of elements: {})'.format(a.shape[0]))
plt.hist(b, bins=100, label='Array 2 (number of elements: {})'.format(b.shape[0]))
plt.legend()
plt.show()
plt.close()

如何在 matplotlib 中仅“本地”更改字体大小?

编辑:抱歉,如果输出看起来令人困惑,但小字体大小的部分不应该是上或下,它应该更小。

【问题讨论】:

  • 使用带上标的乳胶语法text $^\mathrm{small text}$
  • @AndrasDeak 这对我不起作用,因为我使用字符串格式并且收到错误消息 unexpected '{' in field name
  • 你必须像往常一样转义大括号。 rf'text $^\mathrm{{{a.shape[0]}}}$'。一对大括号是字面大括号,第三个是格式。

标签: python numpy matplotlib font-size


【解决方案1】:

我怀疑您是否可以直接使用 matplotlib 来更改字体大小中间标签,但您可以使用 LaTeX 语法添加上标,如下所示:

import numpy as np
from matplotlib import pyplot as plt

a = np.random.rand(100)
b = np.random.rand(250)
plt.hist(a, bins=100, label=r'Array 1 $^\mathrm{{(number of elements:\ {})}}$'.format(a.shape[0]))
plt.hist(b, bins=100, label=r'Array 1 $^\mathrm{{(number of elements:\ {})}}$'.format(b.shape[0]))
plt.legend()
plt.show()

请注意,在格式字符串中需要双括号来获取文字括号,以及在数学模式中需要添加的 '\ '。 (如果您使用 LaTeX 渲染,字体实际上可能会有所不同:\mathrm{} 给您一个衬线字体。您可以尝试使用\mathsf{} 代替 sans,或者使用 \mathrm{} 将整个标签文本置于数学模式以获得一致的外观。这似乎与默认渲染引擎无关。)

如果您不想偏移小文本的基线,您可以使用乳胶大小说明符,例如\scriptsize\footnotesize\tiny 等(在数学模式下,\scriptstyle\scriptscriptstyle 对应 to this answer on tex.SE)。您需要启用 LaTeX 渲染才能使其正常工作,这将影响您后续的所有图形:

# enable TeX rendering for all subsequent figures
plt.rc('text', usetex=True)

plt.hist(a, bins=100, label=r'Array 1 \footnotesize (number of elements: {})'.format(a.shape[0]))
plt.hist(b, bins=100, label=r'Array 2 \scriptsize (number of elements: {})'.format(b.shape[0]))
plt.legend()
plt.show()

\scriptsize 上面的两个选项可能是您正在寻找的:

还有一些与您的问题无关的旁注:

  1. 一维数组使用a.size 而不是a.shape[0]
  2. 考虑使用 f 字符串(在 Python 3.6 中添加),它们通常会使代码更具可读性:rf"Array 2 \scriptsize (number of elements: {b.size})"

(有趣的是,根据您对问题的看法,预期结果会有所不同:this is from desktopthis is mobile。后者看起来需要上标。)

【讨论】:

  • 对不起,我的回答的第二部分实际上不起作用。我暂时把它删了。
  • 啊,真可惜。我刚刚尝试了您的评论,并且 - 如果我可以这样说 - ^ 看起来并不好。但是,如果您发现某事没有(例如,您让\fontsize 等运行),我很想知道它。
  • @Hermi 这是你的问题在移动设备上的样子(我第一次看到它,这就是为什么我只留下评论):i.stack.imgur.com/YGPga.jpg。它看起来就像上标版本 :) 我找到了一种设置字体大小的方法,但老实说它看起来并没有好多少。我稍后会更新我的答案。
  • @Hermi 从头开始​​,我们不需要数学模式来工作,结果看起来还不错。答案已更新。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-03-04
  • 1970-01-01
  • 2022-09-10
  • 2021-08-25
  • 2012-12-21
  • 2019-09-06
  • 2018-01-24
相关资源
最近更新 更多