1. 程式人生 > >Matplotlib(三) rcParams 自定義樣式控制

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(<style-name> )重用自定義樣式表。預設情況下,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()