Task5:第五回:样式色彩秀芳华
樣式色彩秀芳華
- 1、matplotlib的繪圖樣式(style)
- 1.1、matplotlib預(yù)先定義樣式
- 1.2、用戶自定義stylesheet
- 1.3、設(shè)置rcparams
- 1.4、修改 matplotlibrc
- 2、matplotlib的色彩設(shè)置(color)
- 2.1、RGB或RGBA
- 2.2、HEX RGB 或 RGBA
- 2.3、灰度色階
- 2.4、單字符基本顏色
- 2.5、顏色名稱
- 2.6、使用colormap設(shè)置一組顏色
- 2.6.1、順序(Sequential)
- 2.6.2、發(fā)散(Diverging)
- 2.6.3、循環(huán)(Cyclic)
- 2.6.4、定性(Qualitative)
- 2.6.5、雜色(Miscellaneous)
- 3、思考題
- 3.1、使用 LinearSegmentedColormap 的 from_list 方法創(chuàng)建 colormap
- 3.2、使用 ListedColormap 自定義 colormap
教程來(lái)源:https://datawhalechina.github.io/fantastic-matplotlib
參考資料:
1、Python數(shù)據(jù)可視化matplotlib:第五回:樣式色彩秀芳華_林遠(yuǎn)夏的博客-程序員秘密:https://url.cy/wryWK2
2、學(xué)會(huì)這6個(gè)可視化配色基本技巧,還原數(shù)據(jù)本身的意義:https://zhuanlan.zhihu.com/p/88892542
3、RGB顏色和HEX顏色之間是可以一一對(duì)應(yīng)的,以下網(wǎng)址提供了兩種色彩表示方法的轉(zhuǎn)換工具:https://www.colorhexa.com/
4、[matplotlib] 顏色設(shè)置及Matplotlib顏色對(duì)照表:https://zhuanlan.zhihu.com/p/65220518
5、matplotlib基本顏色演示:https://www.matplotlib.org.cn/gallery/color/color_demo.html
6、五種colormap的字符串表示和顏色圖的對(duì)應(yīng)關(guān)系:https://matplotlib.org/stable/tutorials/colors/colormaps.html
7、rcParam支持的參數(shù)列表可以參照官方文檔的相關(guān)說(shuō)明:
https://matplotlib.org/stable/api/matplotlib_configuration_api.html?highlight=rcparams#matplotlib.rcParams
詳細(xì)介紹matplotlib中樣式和顏色的使用。
繪圖樣式和顏色是豐富可視化圖表的重要手段,因此熟練掌握本章可以讓可視化圖表變得更美觀,突出重點(diǎn)和凸顯藝術(shù)性。
關(guān)于繪圖樣式,常見的有3種方法,分別是修改預(yù)定義樣式,自定義樣式和rcparams。
關(guān)于顏色使用,本章介紹了常見的5種表示單色顏色的基本方法,以及colormap多色顯示的方法。
1、matplotlib的繪圖樣式(style)
在matplotlib中,要想設(shè)置繪制樣式,最簡(jiǎn)單的方法是在繪制元素時(shí)單獨(dú)設(shè)置樣式。
但是有時(shí)候,當(dāng)用戶在做專題報(bào)告時(shí),往往會(huì)希望保持整體風(fēng)格的統(tǒng)一而不用對(duì)每張圖一張張修改,因此matplotlib庫(kù)還提供了四種批量修改全局樣式的方式
1.1、matplotlib預(yù)先定義樣式
matplotlib貼心地提供了許多內(nèi)置的樣式供用戶使用,使用方法很簡(jiǎn)單,只需在python腳本的最開始輸入想使用style的名稱即可調(diào)用,嘗試調(diào)用不同內(nèi)置樣式,比較區(qū)別
matplotlib究竟內(nèi)置了那些樣式供使用呢?總共以下26種豐富的樣式可供選擇,如下:
# 默認(rèn)樣式 plt.style.use('default') plt.plot([1,2,3,4],[2,3,4,5]); plt.style.use('ggplot') plt.plot([1,2,3,4],[2,3,4,5]); print(plt.style.available) len(plt.style.available) ['Solarize_Light2', '_classic_test_patch', '_mpl-gallery', '_mpl-gallery-nogrid', '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']28 # 繪制所有風(fēng)格圖fig = plt.figure(figsize = (60, 30)) for i in range(len(plt.style.available)):plt.subplot(4, 7, i+1)plt.title(plt.style.available[i],fontsize=50,color='k')plt.style.use(plt.style.available[i])plt.plot([1,2,3,4],[2,3,4,5])fig.suptitle('style',fontsize=100, color='b',fontweight='bold') plt.tight_layout() plt.show()1.2、用戶自定義stylesheet
在任意路徑下創(chuàng)建一個(gè)后綴名為mplstyle的樣式清單,編輯文件添加以下樣式內(nèi)容:
axes.titlesize : 24
axes.labelsize : 20
lines.linewidth : 3
lines.markersize : 10
xtick.labelsize : 16
ytick.labelsize : 16
1.3、設(shè)置rcparams
我們還可以通過(guò)修改默認(rèn)rc設(shè)置的方式改變樣式,所有rc設(shè)置都保存在一個(gè)叫做 matplotlib.rcParams的變量中。
修改過(guò)后再繪圖,可以看到繪圖樣式發(fā)生了變化。
plt.style.use('default') # 恢復(fù)到默認(rèn)樣式 plt.plot([1,2,3,4],[2,3,4,5]); # 修改參數(shù) 設(shè)置mpl.rcParams['lines.linewidth'] = 2 mpl.rcParams['lines.linestyle'] = '--' plt.plot([1,2,3,4],[2,3,4,5]);另外matplotlib也還提供了一種更便捷的修改樣式方式,可以一次性修改多個(gè)樣式。
mpl.rc('lines', linewidth=4, linestyle='-.') plt.plot([1,2,3,4],[2,3,4,5]); mpl.rc('lines', linewidth=4, linestyle='-.') mpl.rc('axes', titlesize = 24, labelsize = 30) plt.xlabel('xlabel') plt.title("This is title") plt.plot([1,2,3,4],[2,3,4,5]);1.4、修改 matplotlibrc
由于matplotlib是使用matplotlibrc文件來(lái)控制樣式的,也就是上一節(jié)提到的rc setting,所以我們還可以通過(guò)修改matplotlibrc文件的方式改變樣式。
# 查找matplotlibrc文件的路徑 mpl.matplotlib_fname() 'E:\\Anaconda3\\envs\\pytorch\\lib\\site-packages\\matplotlib\\mpl-data\\matplotlibrc'2、matplotlib的色彩設(shè)置(color)
在可視化中,如何選擇合適的顏色和搭配組合也是需要仔細(xì)考慮的,色彩選擇要能夠反映出可視化圖像的主旨。
從可視化編碼的角度對(duì)顏色進(jìn)行分析,可以將顏色分為色相、亮度和飽和度三個(gè)視覺通道。
通常來(lái)說(shuō):
色相: 沒有明顯的順序性、一般不用來(lái)表達(dá)數(shù)據(jù)量的高低,而是用來(lái)表達(dá)數(shù)據(jù)列的類別。
明度和飽和度: 在視覺上很容易區(qū)分出優(yōu)先級(jí)的高低、被用作表達(dá)順序或者表達(dá)數(shù)據(jù)量視覺通道。
具體關(guān)于色彩理論部分的知識(shí),不屬于本教程的重點(diǎn),請(qǐng)參閱有關(guān)拓展材料學(xué)習(xí):https://zhuanlan.zhihu.com/p/88892542
2.1、RGB或RGBA
# 設(shè)置繪圖樣式 plt.style.use('default') # 顏色用[0,1]之間的浮點(diǎn)數(shù)表示,四個(gè)分量按順序分別為(red, green, blue, alpha),其中alpha透明度可省略 plt.plot([1,2,3],[4,5,6],color=(0.1, 0.2, 0.5)) plt.plot([4,5,6],[1,2,3],color=(0.1, 0.2, 0.5, 0.5));2.2、HEX RGB 或 RGBA
# 用十六進(jìn)制顏色碼表示,同樣最后兩位表示透明度,可省略plt.plot([1,2,3],[4,5,6],color='#0f0f0f') plt.plot([4,5,6],[1,2,3],color='#0f0f0f80');RGB顏色和HEX顏色之間是可以一一對(duì)應(yīng)的,以下網(wǎng)址提供了兩種色彩表示方法的轉(zhuǎn)換工具:https://www.colorhexa.com/
2.3、灰度色階
# 當(dāng)只有一個(gè)位于[0,1]的值時(shí),表示灰度色階plt.plot([1,2,3],[4,5,6],color='0.5');2.4、單字符基本顏色
# matplotlib有八個(gè)基本顏色,可以用單字符串來(lái)表示, #分別是'b', 'g', 'r', 'c', 'm', 'y', 'k', 'w',對(duì)應(yīng)的是blue, green, red, cyan, magenta, yellow, black, and white的英文縮寫plt.plot([1,2,3],[4,5,6],color='m');2.5、顏色名稱
# matplotlib提供了顏色對(duì)照表,可供查詢顏色對(duì)應(yīng)的名稱plt.plot([1,2,3],[4,5,6],color='tan');2.6、使用colormap設(shè)置一組顏色
有些圖表支持使用colormap的方式配置一組顏色,從而在可視化中通過(guò)色彩的變化表達(dá)更多信息。
在matplotlib中,colormap共有五種類型:
順序(Sequential):通常使用單一色調(diào),逐漸改變亮度和顏色漸漸增加,用于表示有順序的信息
發(fā)散(Diverging):改變兩種不同顏色的亮度和飽和度,這些顏色在中間以不飽和的顏色相遇;當(dāng)繪制的信息具有關(guān)鍵中間值(例如地形)或數(shù)據(jù)偏離零時(shí),應(yīng)使用此值。
循環(huán)(Cyclic):改變兩種不同顏色的亮度,在中間和開始/結(jié)束時(shí)以不飽和的顏色相遇。用于在端點(diǎn)處環(huán)繞的值,例如相角,風(fēng)向或一天中的時(shí)間。
定性(Qualitative):常是雜色,用來(lái)表示沒有排序或關(guān)系的信息。
雜色(Miscellaneous):一些在特定場(chǎng)景使用的雜色組合,如彩虹,海洋,地形等。
在以下官網(wǎng)頁(yè)面可以查詢上述五種colormap的字符串表示和顏色圖的對(duì)應(yīng)關(guān)系:https://matplotlib.org/stable/tutorials/colors/colormaps.html
import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt from colorspacious import cspace_converter cmaps = {}gradient = np.linspace(0, 1, 256) gradient = np.vstack((gradient, gradient))def plot_color_gradients(category, cmap_list):# Create figure and adjust figure height to number of colormapsnrows = len(cmap_list)figh = 0.35 + 0.15 + (nrows + (nrows - 1) * 0.1) * 0.22fig, axs = plt.subplots(nrows=nrows + 1, figsize=(6.4, figh))fig.subplots_adjust(top=1 - 0.35 / figh, bottom=0.15 / figh,left=0.2, right=0.99)axs[0].set_title(f'{category} colormaps', fontsize=14)for ax, name in zip(axs, cmap_list):ax.imshow(gradient, aspect='auto', cmap=mpl.colormaps[name])ax.text(-0.01, 0.5, name, va='center', ha='right', fontsize=10,transform=ax.transAxes)# Turn off *all* ticks & spines, not just the ones with colormaps.for ax in axs:ax.set_axis_off()# Save colormap list for later.cmaps[category] = cmap_list2.6.1、順序(Sequential)
# 順序(Sequential):通常使用單一色調(diào),逐漸改變亮度和顏色漸漸增加,用于表示有順序的信息plot_color_gradients('Perceptually Uniform Sequential',['viridis', 'plasma', 'inferno', 'magma', 'cividis']) plot_color_gradients('Sequential',['Greys', 'Purples', 'Blues', 'Greens', 'Oranges', 'Reds','YlOrBr', 'YlOrRd', 'OrRd', 'PuRd', 'RdPu', 'BuPu','GnBu', 'PuBu', 'YlGnBu', 'PuBuGn', 'BuGn', 'YlGn']) plot_color_gradients('Sequential (2)',['binary', 'gist_yarg', 'gist_gray', 'gray', 'bone','pink', 'spring', 'summer', 'autumn', 'winter', 'cool','Wistia', 'hot', 'afmhot', 'gist_heat', 'copper'])2.6.2、發(fā)散(Diverging)
plot_color_gradients('Diverging',['PiYG', 'PRGn', 'BrBG', 'PuOr', 'RdGy', 'RdBu', 'RdYlBu','RdYlGn', 'Spectral', 'coolwarm', 'bwr', 'seismic'])2.6.3、循環(huán)(Cyclic)
plot_color_gradients('Cyclic', ['twilight', 'twilight_shifted', 'hsv'])2.6.4、定性(Qualitative)
plot_color_gradients('Qualitative',['Pastel1', 'Pastel2', 'Paired', 'Accent', 'Dark2','Set1', 'Set2', 'Set3', 'tab10', 'tab20', 'tab20b','tab20c'])2.6.5、雜色(Miscellaneous)
plot_color_gradients('Miscellaneous',['flag', 'prism', 'ocean', 'gist_earth', 'terrain','gist_stern', 'gnuplot', 'gnuplot2', 'CMRmap','cubehelix', 'brg', 'gist_rainbow', 'rainbow', 'jet','turbo', 'nipy_spectral', 'gist_ncar'])plt.show() # 示例 # RdPu為Sequential子類x = np.random.randn(50) y = np.random.randn(50) plt.scatter(x,y,c=x,cmap='RdPu');plt.scatter(x,y,c=x,cmap='flag');3、思考題
學(xué)習(xí)如何自定義colormap,并將其應(yīng)用到任意一個(gè)數(shù)據(jù)集中,繪制一幅圖像,注意colormap的類型要和數(shù)據(jù)集的特性相匹配,并做簡(jiǎn)單解釋
# 參考鏈接:Python數(shù)據(jù)可視化matplotlib:第五回:樣式色彩秀芳華_林遠(yuǎn)夏的博客-程序員秘密:https://url.cy/wryWK2 # 三種不同的顏色,分別代表了鳶尾花三種類型的數(shù)據(jù),這里使用的是sklearn庫(kù)自帶的數(shù)據(jù),方便處理。import pandas as pd #數(shù)據(jù)分析、處理 import numpy as np #科學(xué)計(jì)算包 import matplotlib.pyplot as plt #畫圖from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split iris_dataset = load_iris() # sklearn已經(jīng)整理了Iris數(shù)據(jù)集,使用load_iris函數(shù)可以直接下載,使用;#導(dǎo)入數(shù)據(jù) iris = load_iris() X = iris.data[:,:2] #指選擇第一個(gè)和第三個(gè)特征作為輸入 y = iris.target # 輸出x_min,x_max = X[:,0].min()-.5, X[:,0].max()+.5 y_min,y_max = X[:,1].min()-.5, X[:,1].max()+.5plt.figure(2,figsize=(8,6)) plt.clf()plt.scatter(X[:,0],X[:,1],c=y,cmap=plt.cm.Set1,edgecolor='k') plt.xlabel('Sepal length') plt.ylabel('Sepal width')#以花瓣長(zhǎng)度和寬度為橫縱坐標(biāo)繪制一個(gè)圖plt.xlim(x_min, x_max) plt.ylim(y_min, y_max) plt.xticks(()) plt.yticks(())plt.show()使用 matplotlib 自定義Colormap
自定義 colormap 通常要使用 matplotlib.colors 模塊中提供的函數(shù)和方法。
matplotlib.colors 是用來(lái)轉(zhuǎn)換數(shù)字列表或顏色參數(shù)為 RGB 或 RGBA 的模塊。RGB 和 RGBA 是具有3個(gè)或4個(gè)浮點(diǎn)數(shù)且數(shù)值在 [0, 1] 之間的序列。
創(chuàng)建 colormap 時(shí)通常需要以下兩步:
1、使用 Normalize 實(shí)例或子類將數(shù)據(jù)數(shù)組歸一化為 [0 1]之間的數(shù)組
2、使用 Colormap 子類的實(shí)例進(jìn)行數(shù)據(jù)和顏色的映射
模塊中提供了以下兩個(gè)函數(shù)創(chuàng)建 colormap:
LinearSegmentedColormap :有內(nèi)置 colormap 實(shí)例均由此函數(shù)創(chuàng)建,但也可以自定義colormap
ListedColormap :從顏色列表創(chuàng)建 colormap
3.1、使用 LinearSegmentedColormap 的 from_list 方法創(chuàng)建 colormap
參考鏈接:
python colormap_Python matplotlib的使用并自定義colormap的方法:https://blog.csdn.net/weixin_39739661/article/details/110753542
使用 matplotlib 自定義Colormap:https://cloud.tencent.com/developer/article/1618345
# 顯示原圖片 import matplotlib.pyplot as plt # plt 用于顯示圖片 import matplotlib.image as mpimg # mpimg 用于讀取圖片 import numpy as nplena = mpimg.imread('img_188.jpg') # 讀取和代碼處于同一目錄下的 lena.png # 此時(shí) lena 就已經(jīng)是一個(gè) np.array 了,可以對(duì)它進(jìn)行任意處理 lena.shape #(512, 512, 3)plt.imshow(lena) # 顯示圖片 plt.axis('off') # 不顯示坐標(biāo)軸 (-0.5, 4023.5, 3035.5, -0.5) from matplotlib.colors import LinearSegmentedColormap import random import matplotlib.image as mpimg# R, G, B 三色 colors = [(1, 0, 0), (0, 1, 0), (0, 0, 1)]# 用于進(jìn)行 colormap 插值,表示 colormap 顏色區(qū)間 n_bins = [3, 6, 10, 100] # colormap 名 cmap_name = 'my_cmap'fig, axs = plt.subplots(2, 2, figsize=(6, 9)) fig.subplots_adjust(left=0.02, bottom=0.06, right=0.95, top=0.94, wspace=0.05)data=mpimg.imread('img_188.jpg')for n_bin, ax in zip(n_bins, axs.ravel()):# 創(chuàng)建 colormapcm = LinearSegmentedColormap.from_list(cmap_name, colors, N=n_bin)# n_bin 越小,插值得到的顏色區(qū)間越少im = ax.imshow(data, interpolation='nearest', origin='lower', cmap=cm)ax.set_title("N bins: %s" % n_bin)fig.colorbar(im, ax=ax)plt.axis('off') # 不顯示坐標(biāo)軸 plt.show() # 添加colormap的對(duì)象是灰度圖,可以變成熱量圖,從而更加明顯的發(fā)現(xiàn)一些規(guī)律,適用于一些雷達(dá)圖像等from PIL import Image# 將彩色圖片轉(zhuǎn)換成黑白圖片 im=Image.open("img_188.jpg") im1 = im.convert('L')# 保存圖片 # im.save("image.jpg") # im1.show()plt.subplot(1,2,1) plt.imshow(im) plt.axis('off') # 不顯示坐標(biāo)軸plt.subplot(1,2,2) plt.imshow(im1); plt.axis('off') # 不顯示坐標(biāo)軸 (-0.5, 4023.5, 3035.5, -0.5) # 從圖片中讀取數(shù)據(jù),轉(zhuǎn)換成colormap圖import matplotlib.pyplot as plt import matplotlib.image as mpimg import matplotlib as mpl from PIL import Image import numpy as np# 自定義colormap def colormap():return mpl.colors.LinearSegmentedColormap.from_list('cmap',['#FFFFFF', '#98F5FF', '#00FF00', '#FFFF00','#FF0000', '#8B0000'], 256)# 讀取圖 plt.subplot(1, 2, 1) data=mpimg.imread('img_188.jpg') plt.imshow(data);# 如果需要固定colorbar的范圍,可以設(shè)置參數(shù)vmin,vmax,具體參考 #http://matplotlib.org/api/image_api.html# 設(shè)定每個(gè)圖的colormap和colorbar所表示范圍是一樣的,即歸一化 plt.subplot(1, 2, 2) plt.imsave('colormap.jpg',data, cmap=colormap()) plt.imshow(data, cmap=colormap());# 這里沒有顯示出來(lái)colorbar的數(shù)值分布,得到的圖像是等大的3.2、使用 ListedColormap 自定義 colormap
import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl import matplotlib.colors as colors# 生成圖片格式自定義 def colormap():# 白青綠黃紅cdict = ['#FFFFFF', '#9ff113', '#5fbb44', '#f5f329', '#e50b32']# 按照上面定義的colordict,將數(shù)據(jù)分成對(duì)應(yīng)的部分,indexed:代表順序return colors.ListedColormap(cdict, 'indexed')# 加載數(shù)據(jù) data=mpimg.imread('img_188.jpg') fig = plt.figure()# 加載圖片設(shè)置my_cmap = colormap()# 第一個(gè)子圖,按照默認(rèn)配置 ax = fig.add_subplot(221) ax.imshow(data)# 第二個(gè)子圖,使用api自帶的colormap ax = fig.add_subplot(222) cmap = mpl.cm.bwr # 藍(lán),白,紅 ax.imshow(data, cmap=cmap)# 第三個(gè)子圖增加一個(gè)colorbar ax = fig.add_subplot(223) cmap = mpl.cm.winter # 冬季風(fēng)格 im = ax.imshow(data, cmap=my_cmap) plt.colorbar(im) # 增加colorbar# 第四個(gè)子圖可以調(diào)整colorbar ax = fig.add_subplot(224) cmap = mpl.cm.rainbow# 這里設(shè)置colormap的固定值 norm = mpl.colors.Normalize(vmin=-1, vmax=1) im=ax.imshow(data,cmap=cmap) plt.colorbar(im,cmap=cmap, norm=norm,ticks=[-1,0,1])# 顯示 plt.show()總結(jié)
以上是生活随笔為你收集整理的Task5:第五回:样式色彩秀芳华的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 说说图片加载不出来_晒晒我的新家,朋友都
- 下一篇: yy自动语音接待机器人_人脸签到、发言记