>>> plt.style.available
['Solarize_Light2', '_classic_test_patch', 'bmh', 'classic', 'dark_background', 'fast', 'fivethirtyeight', 'ggplot', 'grayscale', 'seaborn', 'seaborn-bright', 'seaborn-colorblind', 'seaborn-dark', 'seaborn-dark-palette', 'seaborn-darkgrid', 'seaborn-deep', 'seaborn-muted', 'seaborn-notebook', 'seaborn-paper', 'seaborn-pastel', 'seaborn-poster', 'seaborn-talk', 'seaborn-ticks', 'seaborn-white', 'seaborn-whitegrid', 'tableau-colorblind10']
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> plt.style.use('dark_background')
>>> plt.plot(np.sin(np.linspace(0, 2 * np.pi)), 'r-o')
>>> plt.show()
輸出結(jié)果如下
不指定style的情況下,默認(rèn)的輸出結(jié)果如下
可以看到,簡(jiǎn)單的修改主題,就可以得到外觀不一樣的圖片。那么主題到底設(shè)定了哪些元素的樣式呢?可以通過(guò)以下方式來(lái)查看每個(gè)主題的具體定義
>>> import matplotlib
>>> import matplotlib.style
>>> print(matplotlib.style.library['dark_background'])
axes.edgecolor: white
axes.facecolor: black
axes.labelcolor: white
axes.prop_cycle: cycler('color', ['#8dd3c7', '#feffb3', '#bfbbd9', '#fa8174', '#81b1d2', '#fdb462', '#b3de69', '#bc82bd', '#ccebc4', '#ffed6f'])
figure.edgecolor: black
figure.facecolor: black
grid.color: white
lines.color: white
patch.edgecolor: white
savefig.edgecolor: black
savefig.facecolor: black
text.color: white
xtick.color: white
ytick.color: white
可以看到,對(duì)于axes, figure, grid, lines, pathch, text, tick等元素進(jìn)行了定義。當(dāng)然,具體到每個(gè)style, 其定義的具體屬性不盡相同。
在內(nèi)置style的基礎(chǔ)上,我們會(huì)需要對(duì)其中的部分屬性進(jìn)行修改,可以通過(guò)rcParams字典來(lái)實(shí)現(xiàn),用法如下
>>> import numpy as np
>>> import matplotlib as mpl
>>> import matplotlib.pyplot as plt
>>> plt.style.use('ggplot')
>>> mpl.rcParams['xtick.color'] = 'red'
>>> mpl.rcParams['ytick.color'] = 'blue'
>>> plt.plot(np.sin(np.linspace(0, 2 * np.pi)), 'r-o')
>>> plt.show()
只使用ggplot主題時(shí),輸出結(jié)果如下
當(dāng)我們通過(guò)rcParams修改了對(duì)應(yīng)的屬性之后,輸出結(jié)果如下
本質(zhì)上,style就是對(duì)matplotlibrc配置文件中的部分屬性進(jìn)行了預(yù)先定義,而rcParams的作用也是對(duì)該配置文件中的屬性進(jìn)行定義,而且優(yōu)先級(jí)是最高的,所以可以覆蓋style中已經(jīng)定義好的值。
當(dāng)我們自定義的屬性過(guò)多且經(jīng)常使用時(shí),可以訂制一個(gè)自己的style, 其實(shí)內(nèi)置的style也是以文件的形式保存在安裝目錄下,截圖如下
我們只需要在該目錄下創(chuàng)建一個(gè)新的style文件即可,比如將自定義的style命名為new, 在該目錄下創(chuàng)建new.mplstyle文件,然后在文件中設(shè)置幾個(gè)基本屬性,內(nèi)容如下
axes.facecolor: eeeeee
axes.edgecolor: bcbcbc
axes.grid : True
接下來(lái), 重新啟動(dòng)python, 就可以使用我們自定義的style了,代碼如下
>>> import numpy as np
>>> import matplotlib as mpl
>>> import matplotlib.pyplot as plt
>>> plt.style.use('new')
如果有一套成熟的屬性設(shè)置,采用這種方式是最佳選擇。
·end·
聯(lián)系客服