【1.4】matplotlib样式

一、matplotlib使用默认样式

matplotlib有很多样式,举个例子,ggplot(跟R中的ggplot类似)

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
plt.style.use('ggplot')
data = np.random.randn(50)

显示所有可用的样式,

print(plt.style.available)

输出:

['seaborn-ticks', 'ggplot', 'dark_background', 'bmh', 'seaborn-poster', 'seaborn-notebook', 'fast', 'seaborn', 'classic', 'Solarize_Light2', 'seaborn-dark', 'seaborn-pastel', 'seaborn-muted', '_classic_test', 'seaborn-paper', 'seaborn-colorblind', 'seaborn-bright', 'seaborn-talk', 'seaborn-dark-palette', 'tableau-colorblind10', 'seaborn-darkgrid', 'seaborn-whitegrid', 'fivethirtyeight', 'grayscale', 'seaborn-white', 'seaborn-deep']

二、自定义样式

在mpl_configdir/stylelib文件夹中添加自定义的<style-name>.mplstyle 文件, 然后也可以通过 style.use(<style-name>) 来调用style。默认的 mpl_configdir 应该在 ~/.config/matplotlib, 但可以通过 matplotlib.get_configdir() 来检查对应的位置

或者需要自己来构建这个文件夹。或者自己重定向文件夹位置

如果mpl_configdir/stylelib 中自定义的style的名字跟matplotlib中相同,则会覆盖matplotlib的stype

比如,在mpl_configdir/stylelib/presentation.mplstyle 文件中做如下修改:

axes.titlesize : 24
axes.labelsize : 20
lines.linewidth : 3
lines.markersize : 10
xtick.labelsize : 16
ytick.labelsize : 16

如果想要paper那种样式,可以

>>> import matplotlib.pyplot as plt
>>> plt.style.use('presentation')

三、组合样式

有时候需要一些组合样式,比如一个style定义颜色,另一个style定义大小,这个时候就可以组合着来用,当然,右边的style如果跟左边的有相同的元素的话,会进行覆盖。

>>> import matplotlib.pyplot as plt
>>> plt.style.use(['dark_background', 'presentation'])

四、零时用样式

如果只是希望在某些位置用样式,但不要改变全局的样式,则可以通过with 限制style的位置

with plt.style.context('dark_background'):
    plt.plot(np.sin(np.linspace(0, 2 * np.pi)), 'r-o')
plt.show()

五、matplotlib rcParams

动态的rc设置

所有的rc参数都存储在matplotlib.rcParams中,在作图过程,可以直接进行修改,修改后则全局生效。

mpl.rcParams['lines.linewidth'] = 2
mpl.rcParams['lines.color'] = 'r'
plt.plot(data)

或者

plt.rcParams.update({'figure.autolayout': True})

批量修改

可以通过mpl.rc函数批量进行修改

mpl.rc('lines', linewidth=4, color='g')
plt.plot(data)

恢复默认的参数

mpl.rcdefaults() 和 matplotlib.rc_file_defaults()

其中 rcdefaults() 是恢复成 matplotlib 内建的样式,rc_file_defaults() 是恢复成最初导入的 rc 文件定义的样式。

修改指定的axes

labels = ax.get_xticklabels()
plt.setp(labels, rotation=45, horizontalalignment='right')

六、参数文件的顺序

  1. 当前工作路径下的matplotlibrc
  2. $MATPLOTLIBRC 或 $MATPLOTLIBRC/matplotlibrc.
  3. 用户自定义的路径(可以通过 matplotlib.get_configdir() 来查询,通过 $MPLCONFIGDIR 环境变量设置):
  • On Linux and FreeBSD, it looks in .config/matplotlib/matplotlibrc (or $XDG_CONFIG_HOME/matplotlib/matplotlibrc) if you’ve customized your environment.
  • On other platforms, it looks in .matplotlib/matplotlibrc.
  1. INSTALL/matplotlib/mpl-data/matplotlibrc, 例如:linux上的 /usr/lib/python3.7/site-packages , 或windows上的 C:\Python37\Lib\site-packages。每次重新安装matplotlib,这部分都会被覆盖。

如果找到了matplotlibrc文件,则不会在后面的位置中去搜索。如果想看目前用matplotlibrc文件来自哪,可以

>>> import matplotlib
>>> matplotlib.matplotlib_fname()
'/home/foo/.config/matplotlib/matplotlibrc'

参考资料

药企,独角兽,苏州。团队长期招人,感兴趣的都可以发邮件聊聊:tiehan@sina.cn
个人公众号,比较懒,很少更新,可以在上面提问题,如果回复不及时,可发邮件给我: tiehan@sina.cn