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()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章