使用样式表时如何自定义字体

3

我正在使用 'ggplot' 样式表。这个样式很好,但是我想特定地改变字体风格。是否有可能?

我在文档中找到了有关自定义样式的信息。但是,我只想改变字体而保留其余样式。

此外,是否有人知道如何查看每个 style 的设置详细信息(例如字体、figsize等)?

plt.imshow(ori, vmin = 0, vmax = 300)
plt.style.use('ggplot')
plt.show() 
3个回答

4

合并样式

我认为最优雅的方法是合并样式

例如,您可以在mystyle.mplstyle中定义自己的字体设置(请参见下面的保存位置和示例)。要获取具有自己字体设置的ggplot样式,您只需指定:

plt.style.use(['ggplot', 'mystyle'])

这个解决方案非常优雅,因为它允许在所有绘图中保持一致,并且允许您混合和匹配。

自定义样式保存在哪里?

从我的一个样式 mystyle.mplstyle 中获取可能有以下条目(显然应根据您的需要进行自定义):

font.family  : serif
font.serif   : CMU Serif
font.weight  : bold
font.size    : 18
text.usetex  : true

你应该将它保存在matplotlib的配置目录中。对我来说,这个目录是~/.matplotlib/stylelib/,但请使用...
import matplotlib
matplotlib.get_configdir()

查找操作系统所使用的工具请参见文档。您还可以编写Python函数并将其安装到正确的位置。

如何找到现有样式?

针对您的问题的最后部分,首先需要知道可以使用以下命令获取可用样式列表:

import matplotlib.pyplot as plt
plt.style.available

请查看文档以获取图形表示。
如何检查例如ggplot.mplstyle? 我认为最好的参考是在Matplotlib源代码中。您也可以在系统上找到*.mplstyle文件,但是位置取决于您的操作系统和安装方式。对我来说,
find / -iname 'ggplot.mplstyle' 2>/dev/null

提供

/usr/local/lib/python3.7/site-packages/matplotlib/mpl-data/stylelib/ggplot.mplstyle

或者更一般地,您可以搜索所有样式:

find / -iname '*.mplstyle' 2>/dev/null

对于Windows,我不是专家,但也许上面列出的文件路径可以给你一些查找线索。

安装样式到正确位置的Python脚本

为了将自定义样式安装到正确的位置,您可以编写一个类似以下脚本的脚本:

def copy_style():

    import os
    import matplotlib

    # style definition(s)

    styles = {}

    styles['mystyle.mplstyle'] = '''
font.family          : serif
'''

    # write style definitions

    # directory name where the styles are stored
    dirname = os.path.abspath(os.path.join(matplotlib.get_configdir(), 'stylelib'))

    # make directory if it does not yet exist
    if not os.path.isdir(dirname): os.makedirs(dirname)

    # write all styles
    for fname, style in styles.items():
        open(os.path.join(dirname, fname),'w').write(style)

谢谢!这真的很有用,而且系统化! - sealpuppy

2
是的,这是可能的。您可以通过将字体传递给单个标签来在本地执行此操作。最初的回答。
font = {'fontname':'your font'}
plt.xlabel('xlabel', **hfont)
plt.ylabel('xlabel', **hfont)

最初的回答
或者全球范围内
 import matplotlib.pyplot as plt
 plt.rcParams['font.family'] = 'your font'

1
尝试使用rcParams。
matplotlib.rcParams.update({'font.size': 12})

阅读更多 matplotlib


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接