数据可视化组队学习:《Task02 - 艺术画笔见乾坤》笔记
文章目錄
- 前言
- 1 概述
- 1.1 matplotlib的使用邏輯
- 1.2 matplotlib的三層api
- 1.3 Artist類的結構
- 1.4 matplotlib標準用法
- 2 自定義你的Artist對象
- 2.1 Artist屬性
- 2.2 屬性調用的方式
- 3 基本元素 - primitives
- 3.1 Line2D
- 3.1.1 如何設置Line2D的屬性
- 3.1.2 繪制Line2D
- 3.1.3 errorbar繪制誤差折線圖
- 3.2 patches
- 3.2.1 繪制Rectangle-矩形
- 3.2.3 繪制Polygon-多邊形
- 3.2.3 繪制Wedge-契形
- 3.3 collections-繪制一組對象的集合
- 3.3.1 scatter繪制散點圖
- 3.4 images
- 4 對象容器 - Object container
- 4.1 Figure容器
- 4.2 Axes容器
- 4.2.1 Subplot和Axes的區別
- 4.3 Axis容器
- 4.4 Tick容器
- 作業
- 思考題
- 繪圖題
前言
本文為數據可視化組隊學習:《Task02 - 藝術畫筆見乾坤》筆記。
1 概述
1.1 matplotlib的使用邏輯
跟人類繪圖一樣,用matplotlib也是一樣的步驟:
1.2 matplotlib的三層api
就如房子一般,是從地基一直往屋頂建的,在matplotlib中,也有類似的層次結構:
代表了繪圖區,所有的圖像都是在繪圖區完成的
代表了渲染器,可以近似理解為畫筆,控制如何在 FigureCanvas 上畫圖。
代表了具體的圖表組件,即調用了Renderer的接口在Canvas上作圖。
1、2 處理程序和計算機的底層交互的事項,3 Artist就是具體的調用接口來做出我們想要的圖,比如圖形、文本、線條的設定。所以通常來說,我們95%的時間,都是用來和 matplotlib.artist.Artist 類打交道的。
1.3 Artist類的結構
其中圖形figure、坐標系Axes和坐標軸Axis的關系如下圖所示:
▲ 圖形figure、坐標系Axes和坐標軸Axis的關系1.4 matplotlib標準用法
由圖形figure、坐標系Axes和坐標軸Axis的關系,可以得到matplotlib畫圖的標準方法,還是以建房子為例,從地基到房頂建造:
2 自定義你的Artist對象
2.1 Artist屬性
在圖形中的每一個元素都對應著一個matplotlib Artist,且都有其對應的配置屬性列表。
每個matplotlib Artist都有以下常用屬性:
補充,完整屬性列表:
| alpha | The transparency - a scalar from 0-1 |
| animated | A boolean that is used to facilitate animated drawing |
| axes | The axes that the Artist lives in, possibly None |
| clip_box | The bounding box that clips the Artist |
| clip_on | Whether clipping is enabled |
| clip_path | The path the artist is clipped to |
| contains | A picking function to test whether the artist contains the pick point |
| figure | The figure instance the artist lives in, possibly None |
| label | A text label (e.g., for auto-labeling) |
| picker | A python object that controls object picking |
| transform | The transformation |
| visible | A boolean whether the artist should be drawn |
| zorder | A number which determines the drawing order |
| rasterized | Boolean; Turns vectors into raster graphics (for compression & eps transparency) |
特別有Figure、Axes本身具有一個Rectangle,使用 Figure.patch 和 Axes.patch 可以查看:
# .patch plt.figure().patch plt.axes().patch2.2 屬性調用的方式
既然每個Artist對象都有屬性,那么該如何去查看和修改這些屬性呢?
Artist對象的所有屬性都通過相應的 get_* 和 set_* 函數進行讀寫。
3 基本元素 - primitives
3.1 Line2D
在matplotlib中曲線的繪制,主要是通過類 matplotlib.lines.Line2D 來完成的。
它的基類: matplotlib.artist.Artist
3.1.1 如何設置Line2D的屬性
有三種方法。
3.1.2 繪制Line2D
繪制直線line常用的方法有兩種。
- pyplot方法繪制
- Line2D對象繪制
常用參數:
- xdata:需要繪制的line中點的在x軸上的取值,若忽略,則默認為range(1,len(ydata)+1)
- ydata:需要繪制的line中點的在y軸上的取值
- linewidth:線條的寬度
- linestyle:線型
- color:線條的顏色
- marker:點的標記,詳細可參考markers API 1
- markersize:標記的size
- pyplot方法繪制
這種方法更加簡便。
- Line2D對象繪制
這種方法完美地詮釋了matplotlib畫圖的figure→axes→axis結構。
上述代碼也可用下面的代替:
import matplotlib.pyplot as plt from matplotlib.lines import Line2D fig = plt.figure() ax = fig.add_subplot(111) # 1×1網格,第1子圖x = range(0,5) y = [2,5,7,8,10] line = Line2D(x, y) ax.add_line(line)ax.set(xlim=(min(x), max(x)), ylim=(min(y), max(y)))plt.show()3.1.3 errorbar繪制誤差折線圖
構造方法如下:
matplotlib.pyplot.errorbar(x, y, yerr=None, xerr=None, fmt=’’, ecolor=None, elinewidth=None, capsize=None, barsabove=False, lolims=False, uplims=False, xlolims=False, xuplims=False, errorevery=1, capthick=None, *, data=None, **kwargs)
主要參數:
- x:需要繪制的line中點的在x軸上的取值
- y:需要繪制的line中點的在y軸上的取值
- yerr:指定y軸水平的誤差
- xerr:指定x軸水平的誤差
- fmt:指定折線圖中某個點的顏色,形狀,線條風格,例如‘co–’
- ecolor:指定error bar的顏色
- elinewidth:指定error bar的線條寬度
errorbar的基類是matplotlib.pyplot,所以不需要plot.show().
import numpy as np import matplotlib.pyplot as plt x = np.arange(10) y = 2.5 * np.sin(x / 20 * np.pi) yerr = np.linspace(0.05, 0.2, 10) plt.errorbar(x, y + 3, yerr=yerr, label='both limits (default)')加個 linewidth=10, color='r':
import numpy as np import matplotlib.pyplot as plt x = np.arange(10) y = 2.5 * np.sin(x / 20 * np.pi) yerr = np.linspace(0.05, 0.2, 10) plt.errorbar(x, y + 5,linewidth=10,color='r', yerr=yerr, label='both limits (default)') plt.legend() # 輸出label3.2 patches
matplotlib.patches.Patch類是二維圖形類。它的基類是matplotlib.artist.Artist。
3.2.1 繪制Rectangle-矩形
Rectangle矩形類在官網中的定義是: 通過錨點xy及其寬度和高度生成。
Rectangle本身的主要比較簡單,即xy控制錨點,width和height分別控制寬和高。它的構造函數:
class matplotlib.patches.Rectangle(xy, width, height, angle=0.0, **kwargs)
在實際中最常見的矩形圖是hist直方圖和bar條形圖。
兩種繪制方法:
- 使用plt.hist繪制
- 使用Rectangle矩形類繪制直方圖
- 使用plt.hist繪制
非常簡便。
matplotlib.pyplot.hist(x,bins=None,range=None, density=None, bottom=None, histtype=‘bar’, align=‘mid’, log=False, color=None, label=None, stacked=False, normed=None)
常用的參數:
- x: 數據集,最終的直方圖將對數據集進行統計
- bins: 統計的區間分布
- range: tuple, 顯示的區間,range在沒有給出bins時生效
- density: bool,默認為false,顯示的是頻數統計結果,為True則顯示頻率統計結果,這里需要注意,頻率統計結果=區間數目/(總數*區間寬度),和>- normed效果一致,官方推薦使用density
- histtype: 可選{‘bar’, ‘barstacked’, ‘step’, ‘stepfilled’}之一,默認為bar,推薦使用默認配置,step使用的是梯狀,stepfilled則會對梯狀內部進行填充,效果與bar類似
- align: 可選{‘left’, ‘mid’, ‘right’}之一,默認為’mid’,控制柱狀圖的水平分布,left或者right,會有部分空白區域,推薦使用默認
- log: bool,默認False,即y坐標軸是否選擇指數刻度
- stacked: bool,默認為False,是否為堆積狀圖
- 使用Rectangle矩形類繪制直方圖
個人感覺比較麻煩。
兩種繪制方法:
- 使用plt.bar()繪制
- 使用Rectangle矩形類繪制柱狀圖
- 使用plt.bar()繪制
非常簡便。
matplotlib.pyplot.bar(left, height, alpha=1, width=0.8, color=, edgecolor=, label=, lw=3)
常用的參數:
- left:x軸的位置序列,一般采用range函數產生一個序列,但是有時候可以是字符串
- height:y軸的數值序列,也就是柱形圖的高度,一般就是我們需要展示的數據;
- alpha:透明度,值越小越透明
- width:為柱形圖的寬度,一般這是為0.8即可;
- color或facecolor:柱形圖填充的顏色;
- edgecolor:圖形邊緣顏色
- label:解釋每個圖像代表的含義,這個參數是為legend()函數做鋪墊的,表示該次bar的標簽
- 使用Rectangle矩形類繪制柱狀圖
個人感覺比較麻煩。
3.2.3 繪制Polygon-多邊形
matplotlib.patches.Polygon類是多邊形類。其基類是matplotlib.patches.Patch。
構造函數:
class matplotlib.patches.Polygon(xy, closed=True, **kwargs)
參數說明:
- xy:是一個N×2的numpy array,為多邊形的頂點。
- closed:為True則指定多邊形將起點和終點重合從而顯式關閉多邊形
在使用中,我們直接通過matplotlib.pyplot.fill()來繪制多邊形:
import matplotlib.pyplot as plt x = np.linspace(0, 5 * np.pi, 1000) y1 = np.sin(x) y2 = np.sin(2 * x) plt.fill(x, y1, color = "g", alpha = 0.3)再用一個例子來說明plt.fill能用于繪制多邊形:
import numpy as np import matplotlib.pyplot as pltdef koch_snowflake(order, scale=10):"""Return two lists x, y of point coordinates of the Koch snowflake.Arguments---------order : intThe recursion depth.scale : floatThe extent of the snowflake (edge length of the base triangle)."""def _koch_snowflake_complex(order):if order == 0:# initial triangleangles = np.array([0, 120, 240]) + 90return scale / np.sqrt(3) * np.exp(np.deg2rad(angles) * 1j)else:ZR = 0.5 - 0.5j * np.sqrt(3) / 3p1 = _koch_snowflake_complex(order - 1) # start pointsp2 = np.roll(p1, shift=-1) # end pointsdp = p2 - p1 # connection vectorsnew_points = np.empty(len(p1) * 4, dtype=np.complex128)new_points[::4] = p1new_points[1::4] = p1 + dp / 3new_points[2::4] = p1 + dp * ZRnew_points[3::4] = p1 + dp / 3 * 2return new_pointspoints = _koch_snowflake_complex(order)x, y = points.real, points.imag # 返回實部和虛部return x, y x, y = koch_snowflake(order=5)plt.figure(figsize=(8, 8)) plt.axis('equal') # 把單位長度都變的一樣。這樣做的好處就是對于圓來說更像圓 plt.fill(x, y) plt.show()3.2.3 繪制Wedge-契形
matplotlib.patches.Polygon類是多邊形類。其基類是matplotlib.patches.Patch。
在使用中,我們直接通過matplotlib.pyplot.pie()來繪制契形:
matplotlib.pyplot.pie(x, explode=None, labels=None, colors=None, autopct=None, pctdistance=0.6, shadow=False, labeldistance=1.1, startangle=0, radius=1, counterclock=True, wedgeprops=None, textprops=None, center=0, 0, frame=False, rotatelabels=False, *, normalize=None, data=None)
常用參數:
- x:契型的形狀,一維數組。
- explode:如果不是等于None,則是一個len(x)數組,它指定用于偏移每個楔形塊的半徑的分數。
- labels:用于指定每個契型塊的標記,取值是列表或為None。
- colors:餅圖循環使用的顏色序列。如果取值為>- None,將使用當前活動循環中的顏色。
- startangle:餅狀圖開始的繪制的角度。
- 使用plt.pie()繪制餅狀圖
- figure→axes→axis結構繪制餅狀圖
- wedge繪制餅圖
3.3 collections-繪制一組對象的集合
collections類是用來繪制一組對象的集合,collections有許多不同的子類,如RegularPolyCollection, CircleCollection, Pathcollection, 分別對應不同的集合子類型。其中比較常用的就是散點圖,它是屬于PathCollection子類,scatter方法提供了該類的封裝,根據x與y繪制不同大小或顏色標記的散點圖。
3.3.1 scatter繪制散點圖
最主要的參數:
- x:數據點x軸的位置
- y:數據點y軸的位置
- s:尺寸大小
- c:可以是單個顏色格式的字符串,也可以是一系列顏色
- marker: 標記的類型
其中marker是點的樣式,如圓形、矩形,甚至是字母之類的,詳情請看官網🔗matplotlib.markers
- 使用Axes.scatter()繪制
- 使用plt.scatter()繪制
3.4 images
images是matplotlib中繪制image圖像的類,其中最常用的imshow可以根據數組繪制成圖像。
matplotlib.pyplot.imshow(X, cmap=None, norm=None, aspect=None, interpolation=None, alpha=None, vmin=None, vmax=None, origin=None, extent=None, shape=, filternorm=1, filterrad=4.0, imlim=, resample=None, url=None, *, data=None, **kwargs)
使用imshow畫圖時首先需要傳入一個數組,數組對應的是空間內的像素位置和像素點的值,其中參數interpolation參數可以設置不同的差值方法,具體效果如下:
import matplotlib.pyplot as plt import numpy as np methods = [None, 'none', 'nearest', 'bilinear', 'bicubic', 'spline16','spline36', 'hanning', 'hamming', 'hermite', 'kaiser', 'quadric','catrom', 'gaussian', 'bessel', 'mitchell', 'sinc', 'lanczos']grid = np.random.rand(4, 4) # 4×4大小的圖片fig, axs = plt.subplots(nrows=3, ncols=6, figsize=(9, 6),subplot_kw={'xticks': [], 'yticks': []})for ax, interp_method in zip(axs.flat, methods):ax.imshow(grid, interpolation=interp_method, cmap='afmhot')ax.set_title(str(interp_method))plt.tight_layout() plt.show()interpolation='antialiased'時,有抗鋸齒效果:
import matplotlib.pyplot as plt import numpy as np methods = [None, 'none', 'nearest', 'bilinear', 'bicubic', 'spline16','spline36', 'hanning', 'hamming', 'hermite', 'kaiser', 'quadric','catrom', 'gaussian', 'bessel', 'mitchell', 'sinc', 'lanczos']grid = np.random.rand(4, 4)fig, axs = plt.subplots(nrows=3, ncols=6, figsize=(9, 6),subplot_kw={'xticks': [], 'yticks': []})for ax, interp_method in zip(axs.flat, methods):"""interpolation = 'none' works well when a big image is scaled down, while interpolation = 'nearest' works well when a small image is scaled up.default: 'antialiased'"""ax.imshow(grid, interpolation='antialiased', cmap='afmhot') # cmap: colormap,圖像的顏色樣式ax.set_title(str(interp_method))plt.tight_layout() # 輸出的圖像看起來更舒服 plt.show()參數cmap代表著不同的顏色,舉些例子:
將上文的代碼的cmap='afmhot'修改為cmap='plasma',圖像顏色改變:
4 對象容器 - Object container
容器會包含一些primitives,并且容器還有它自身的屬性。
4.1 Figure容器
注意Figure默認的坐標系是以像素為單位,你可能需要轉換成figure坐標系:(0,0)表示左下點,(1,1)表示右上點。
Figure容器的常見屬性:
- Figure.patch屬性:Figure的背景矩形
- Figure.axes屬性:一個Axes實例的列表(包括Subplot)
- Figure.images屬性:一個FigureImages patch列表
- Figure.lines屬性:一個Line2D實例的列表(很少使用)
- Figure.legends屬性:一個Figure Legend實例列表(不同于Axes.legends)
- Figure.texts屬性:一個Figure Text實例列表
當我們向圖表添加Figure.add_subplot()或者Figure.add_axes()元素時,這些都會被添加到Figure.axes列表中。
既然Figure.axes里面存有subplot和axes,那我們遍歷看看:
import matplotlib.pyplot as plt fig = plt.figure() ax1 = fig.add_subplot(211) # Add an Axes to the figure as part of a subplot arrangement. ax2 = fig.add_axes([1,1,0.2,0.2]) ax3 = fig.add_subplot(212)for ax in fig.axes:ax.grid(True)4.2 Axes容器
matplotlib.axes.Axes是matplotlib的核心。大量的用于繪圖的Artist存放在它內部,并且它有許多輔助方法來創建和添加Artist給它自己。
Axes有許多方法用于繪圖,如.plot()、.text()、.hist()、.imshow()等方法用于創建大多數常見的primitive(如Line2D,Rectangle,Text,Image等等)
和Figure容器類似,Axes包含了一個patch屬性:
import numpy as np import matplotlib.pyplot as plt import matplotlibfig = plt.figure() ax = fig.add_subplot(111) ## Add an Axes to the figure as part of a subplot rect = ax.patch # axes的patch是一個Rectangle實例 rect.set_facecolor('blue')不應該直接通過Axes.lines和Axes.patches列表來添加圖表,還記得嗎?Axes是從Artist來的,所以可以用add_*,使用Axes的輔助方法.add_line()和.add_patch()方法來直接添加。
4.2.1 Subplot和Axes的區別
Subplot就是一個特殊的Axes,其實例是位于網格中某個區域的Subplot實例,Figure.add_subplot(),通過Figure.add_axes([left,bottom,width,height])可以創建一個任意區域的Axes。
4.3 Axis容器
每個Axis都有一個label屬性,也有主刻度列表和次刻度列表。這些ticks是axis.XTick和axis.YTick實例,它們包含著line primitive以及text primitive用來渲染刻度線以及刻度文本。
刻度是動態創建的,只有在需要創建的時候才創建(比如縮放的時候)。Axis也提供了一些輔助方法來獲取刻度文本、刻度線位置等等:
常見的如下:
下面的例子展示了如何調整一些軸和刻度的屬性(忽略美觀度,僅作調整參考):
fig = plt.figure() # 創建一個新圖表 rect = fig.patch # 矩形實例并將其設為黃色 rect.set_facecolor('lightgoldenrodyellow')ax1 = fig.add_axes([0.1, 0.3, 0.4, 0.4]) # 創一個axes對象,從(0.1,0.3)的位置開始,寬和高都為0.4, rect = ax1.patch # ax1的矩形設為灰色 rect.set_facecolor('lightslategray')for label in ax1.xaxis.get_ticklabels(): # 調用x軸刻度標簽實例,是一個text實例label.set_color('red') # 顏色label.set_rotation(45) # 旋轉角度label.set_fontsize(16) # 字體大小for line in ax1.yaxis.get_ticklines():# 調用y軸刻度線條實例, 是一個Line2D實例line.set_color('green') # 顏色line.set_markersize(25) # marker大小line.set_markeredgewidth(2)# marker粗細plt.show()4.4 Tick容器
matplotlib.axis.Tick是從Figure到Axes到Axis到Tick中最末端的容器對象。
y軸分為左右兩個,因此tick1對應左側的軸;tick2對應右側的軸。
x軸分為上下兩個,因此tick1對應下側的軸;tick2對應上側的軸。
下面的例子展示了,如何將Y軸右邊軸設為主軸,并將標簽設置為美元符號且為綠色:
import numpy as np import matplotlib.pyplot as plt import matplotlibfig, ax = plt.subplots() ax.plot(100*np.random.rand(20))# 設置ticker的顯示格式 formatter = matplotlib.ticker.FormatStrFormatter('$%3.2f') # 3.3f:整數部分隨便填(?不太清楚),小數保留2位 ax.yaxis.set_major_formatter(formatter)# 設置ticker的參數,右側為主軸,顏色為綠色 # which=['major','minor','both'] ax.yaxis.set_tick_params(which='major',labelcolor='green',labelleft=False,labelright=True)plt.show()作業
思考題
primitives是各種基本元素,而container是裝基本元素的容器。相同點在于它們都是Artist的子類,都可以通過add_*和set_*來添加和設置屬性。
figure axes axis tick是”由大到小“的,就跟畫畫一樣,figure是畫布,axes是畫筆,axis就是畫的正方形輪廓,tick就是上面的刻度。如圖所示:
繪圖題
子圖排布是 2 * 3 (2行 3列);
線圖可用教程中line2D方法繪制;
需要設置每個子圖的橫坐標和縱坐標刻度;
并設置整個圖的標題,橫坐標名稱,以及縱坐標名稱
總結
以上是生活随笔為你收集整理的数据可视化组队学习:《Task02 - 艺术画笔见乾坤》笔记的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: “大数据与精准营销沙龙”成功在京召开
- 下一篇: 链上存证、链下传输的可信数据共享平台