.matplotlibrc和默认选项

3 投票
1 回答
6701 浏览
提问于 2025-04-18 05:29

我正在学习Python的matplotlib库。现在我开始理解一些基本的细节,比如pylab和pyplot之间的区别,并且我在尝试复制和修改一些图库中的例子。

不过,有一件事我还是不太明白,那就是配置文件matplotlibrc的实际作用。

目前我在Windows 7上使用WinPython 3.3.5.0 64位版本。这个.matplotlibrc文件的位置是WinPython-64bit-3.3.5.0\python-3.3.5.amd64\lib\site-packages\matplotlib\mpl-data\matplotlibrc。

我想开始修改一些选项,比如默认字体,所以我打开了这个文件,发现除了有一行(backend : TkAgg)以外,其他的行都是注释掉的。

所以我想问一下,matplotlib是从哪里获取所有默认值的(比如字体属性)。是否还有其他文件,或者这些值是以某种方式“硬编码”在库里的?谢谢。

1 个回答

4

根据文档和在网站包目录下的 matplotlib\__init__.py 文件中的代码,你可以看到 matplotlibrc 文件的搜索路径是:

Search order:                                                                                                                             

 * current working dir                                                                                                                    
 * environ var MATPLOTLIBRC                                                                                                               
 * HOME/.matplotlib/matplotlibrc                                                                                                          
 * MATPLOTLIBDATA/matplotlibrc

如果在这些路径中找不到文件,就会出现一个警告:

warnings.warn('Could not find matplotlibrc; using defaults')

matplotlibrc 文件只是对现有默认参数的更新。你可以通过以下方式找到这些参数:

from matplotlib.rcsetup import defaultParams

(这显然是在 matplotlib/rcsetup.py 文件中)

__init__.py 文件中,matplotlib 会遍历这个字典,并定义将用于所有脚本和代码的默认 rc 参数:

rcParamsDefault = RcParams([ (key, default) for key, (default, converter) in \
                    defaultParams.iteritems() ])

所以如果你想知道默认值,可以查看:

In [4]: import matplotlib

In [5]: matplotlib.rcParamsDefault
Out[5]: 
{'agg.path.chunksize': 0,
 'animation.bitrate': -1,
 'animation.codec': 'mpeg4',
 'animation.ffmpeg_args': '',
 'animation.ffmpeg_path': 'ffmpeg',
 'animation.frame_format': 'png',
 'animation.mencoder_args': '',
 'animation.mencoder_path': 'mencoder',
 'animation.writer': 'ffmpeg',
 ...

撰写回答