Matplotlib(三) rcParams 自定义样式控制

  在上一篇 python matplotlib入门(二) Matplotlib 作图生命周期 中,其中一个重要环节是 自定义图像(Customizing Matplotlib),从某种角度来讲,其实这几乎包括了我们绘图80%的工作,这篇博客就来探讨如何DIY我们的图像。

  rcParams

  可以在python脚本中动态更改默认的rc设置,或者从python shell以交互方式更改。所有rc设置都存储在一个名为matplotlib.rcParams的类字典变量中,该变量对于matplotlib包是全局的, 其本质是从本地文件matplotlibrc读取数据

import matplotlib as mpl

# 修改方式一
mpl.rcParams['lines.linewidth'] = 2
mpl.rcParams['lines.color'] = 'r'
# 修改方式二
mpl.rc('lines', linewidth=4, color='g')

# 恢复默认参数
mpl.rcdefaults()

  上面我提到一句话, 其本质是从本地文件matplotlibrc读取数据 , 所以接下来我们找到根源,深入探索。

  matplotlib使用matplotlibrc配置文件来自定义各种属性,我们称之为rc settings或rc params, 它可以控制matplotlib中几乎每个属性的默认值:图形大小,dpi,线宽,颜色和样式,轴,轴和网格属性,文本和字体属性等。 matplotlib按以下顺序在四个位置查找matplotlibrc:

  1. matplotlibrc in the current working directory, usually used for specific customizations that you do not want to apply elsewhere.

  2. $MATPLOTLIBRC if it is a file, else $MATPLOTLIBRC/matplotlibrc.

  3. It next looks in a user-specific place, depending on your platform:

    • 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.
  4. *INSTALL*/matplotlib/mpl-data/matplotlibrc, where *INSTALL* is something like /usr/lib/python3.5/site-packages on Linux, and maybe C:\Python35\Lib\site-packages on Windows. Every time you install matplotlib, this file will be overwritten, so if you want your customizations to be saved, please move this file to your user-specific matplotlib directory.

    
    # 查找文件位置
    
    
    >>> import matplotlib
    >>> matplotlib.matplotlib_fname()
    '/home/foo/.config/matplotlib/matplotlibrc'

   在我电脑中,只有第四个路径匹配项,即在安装包的时候生成的,部分内容如下:

# 路径 D:\Python\Lib\site-packages\matplotlib\mpl-data

#### MATPLOTLIBRC FORMAT

## This is a sample matplotlib configuration file - you can find a copy
## of it on your system in
## site-packages/matplotlib/mpl-data/matplotlibrc.  If you edit it
## there, please note that it will be overwritten in your next install.
## If you want to keep a permanent local copy that will not be
## overwritten, place it in the following location:
## unix/linux:
##      $HOME/.config/matplotlib/matplotlibrc or
##      $XDG_CONFIG_HOME/matplotlib/matplotlibrc (if $XDG_CONFIG_HOME is set)
## other platforms:
##      $HOME/.matplotlib/matplotlibrc
##
## See http://matplotlib.org/users/customizing.html#the-matplotlibrc-file for
## more details on the paths which are checked for the configuration file.
##
## This file is best viewed in a editor which supports python mode
## syntax highlighting. Blank lines, or lines starting with a comment
## symbol, are ignored, as are trailing comments.  Other lines must
## have the format
##     key : val ## optional comment
##
## Colors: for the color values below, you can either use - a
## matplotlib color string, such as r, k, or b - an rgb tuple, such as
## (1.0, 0.5, 0.0) - a hex string, such as ff00ff - a scalar
## grayscale intensity such as 0.75 - a legal html color name, e.g., red,
## blue, darkslategray

##### CONFIGURATION BEGINS HERE

## The default backend; one of GTK GTKAgg GTKCairo GTK3Agg GTK3Cairo
## MacOSX Qt4Agg Qt5Agg TkAgg WX WXAgg Agg Cairo GDK PS PDF SVG
## Template.
## You can also deploy your own backend outside of matplotlib by
## referring to the module name (which must be in the PYTHONPATH) as
## 'module://my_backend'.
##
## If you omit this parameter, it will always default to "Agg", which is a
## non-interactive backend.
backend      : TkAgg

## Note that this can be overridden by the environment variable
## QT_API used by Enthought Tool Suite (ETS); valid values are
## "pyqt" and "pyside".  The "pyqt" setting has the side effect of
## forcing the use of Version 2 API for QString and QVariant.

## The port to use for the web server in the WebAgg backend.
#webagg.port : 8988

## The address on which the WebAgg web server should be reachable
#webagg.address : 127.0.0.1

## If webagg.port is unavailable, a number of other random ports will
## be tried until one that is available is found.
#webagg.port_retries : 50

## When True, open the webbrowser to the plot that is shown
#webagg.open_in_browser : True

## if you are running pyplot inside a GUI and your backend choice
## conflicts, we will automatically try to find a compatible one for
## you if backend_fallback is True
#backend_fallback: True

#interactive  : False
#toolbar      : toolbar2   ## None | toolbar2  ("classic" is deprecated)
#timezone     : UTC        ## a pytz timezone string, e.g., US/Central or Europe/Paris

## Where your matplotlib data lives if you installed to a non-default
## location.  This is where the matplotlib fonts, bitmaps, etc reside
#datapath : /home/jdhunter/mpldata


#### LINES
## See http://matplotlib.org/api/artist_api.html#module-matplotlib.lines for more
## information on line properties.
#lines.linewidth   : 1.5     ## line width in points
#lines.linestyle   : -       ## solid line
#lines.color       : C0      ## has no affect on plot(); see axes.prop_cycle
#lines.marker      : None    ## the default marker
#lines.markeredgewidth  : 1.0     ## the line width around the marker symbol
#lines.markersize  : 6            ## markersize, in points
#lines.dash_joinstyle : round        ## miter|round|bevel
#lines.dash_capstyle : butt          ## butt|round|projecting
#lines.solid_joinstyle : round       ## miter|round|bevel
#lines.solid_capstyle : projecting   ## butt|round|projecting
#lines.antialiased : True         ## render lines in antialiased (no jaggies)

   样式表

  rcParams是自定义控制样式最全面也是最细致的方法,但不见得是最佳的方法。因为我们很多时候并不想花费这么多的时间去设置一堆堆参数,于是会想到能不能使用模板呢?呵,聪明又懒惰的人类!怎么可能没有呢!使用样式模板很简单:

plt.style.use('ggplot') # ggplot是其中一种预设样式,会使用R的同学应该非常熟悉

print(plt.style.available) # 查看所有预设样式

自定义样式

  可以通过调用style.use以及样式表的路径或URL来创建自定义样式并使用它们。此外,如果将 .mplstyle文件添加到mpl_configdir / stylelib,则可以通过调用style.use(重用自定义样式表。默认情况下,mpl_configdir应为〜/ .config / matplotlib,但你可以使用matplotlib.get_configdir()查看你的位置,你可能需要创建此目录。

组合样式

   即使用多种样式

>>> import matplotlib.pyplot as plt
>>> plt.style.use(['dark_background', 'presentation'])
临时样式
# 临时样式通过这种上下文的方式实现,在python中非常常见

# ps:在R语言中也有类似的用法
with plt.style.context(('dark_background')):
    plt.plot(np.sin(np.linspace(0, 2 * np.pi)), 'r-o')
plt.show()

你可能感兴趣的:(Python)