matplotlib 高阶之Transformations Tutorial
目錄
- Data coordinates
- Axes coordinates
- Blended transformations 混合坐標系統(tǒng)
- plotting in physical units
- 使用offset transforms 創(chuàng)建陰影效果
- 函數鏈接
之前在legend的使用中,便已經提及了transforms,用來轉換參考系,一般情況下,我們不會用到這個,但是還是了解一下比較好
| "data" | ax.transData | 數據的坐標系統(tǒng),通過xlim, ylim來控制 |
| "axes" | ax.transAxes | Axes的坐標系統(tǒng),(0, 0)代表左下角,(1, 1)代表右上角 |
| "figure" | fig.transFigure | Figure的坐標系統(tǒng),(0, 0)代表左下角,(1, 1)代表右上角 |
| "figure-inches" | fig.dpi_scale_trans | 以inches來表示的Figure坐標系統(tǒng),(0, 0)左下角,而(width, height)表示右上角 |
| "display" | None or IdentityTransform() | 顯示窗口的像素坐標系統(tǒng),(0, 0)表示窗口的左下角,而(width, height)表示窗口的右上角 |
| "xaxis", "yaxis" | ax.get_xaxis_transform(), ax.get_yaxis_transform() | 混合坐標系; 在另一個軸和軸坐標之一上使用數據坐標。沒看懂 |
Data coordinates
最為常見的便是通過set_xlim, 和set_ylim來控制數據坐標
import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as mpatchesx = np.arange(0, 10, 0.005) y = np.exp(-x/2.) * np.sin(2*np.pi*x)fig, ax = plt.subplots() ax.plot(x, y) ax.set_xlim(0, 10) ax.set_ylim(-1, 1)plt.show()你可以通過ax.transData來將你的數據坐標,轉換成再顯示窗口上的像素坐標,單個坐標,或者傳入序列都是被允許的
type(ax.transData) matplotlib.transforms.CompositeGenericTransform ax.transData.transform((5, 0)) #數據坐標(5, 0) 轉換為顯示窗口的像素坐標(221.4, 144.72) 這個玩意兒不一定的 array([221.4 , 144.72]) ax.transData.transform(((5, 0), (2, 3))) array([[221.4 , 144.72],[120.96, 470.88]])你也可以通過使用inverted()來反轉,獲得數據坐標
inv = ax.transData.inverted() type(inv) matplotlib.transforms.CompositeGenericTransform inv.transform((221.4, 144.72)) array([5., 0.])下面是一個比較完整的例子
x = np.arange(0, 10, 0.005) y = np.exp(-x/2.) * np.sin(2*np.pi*x)fig, ax = plt.subplots() ax.plot(x, y) ax.set_xlim(0, 10) ax.set_ylim(-1, 1)xdata, ydata = 5, 0 xdisplay, ydisplay = ax.transData.transform_point((xdata, ydata))bbox = dict(boxstyle="round", fc="0.8") arrowprops = dict(arrowstyle="->",connectionstyle="angle,angleA=0,angleB=90,rad=10")offset = 72 ax.annotate('data = (%.1f, %.1f)' % (xdata, ydata),(xdata, ydata), xytext=(-2*offset, offset), textcoords='offset points',bbox=bbox, arrowprops=arrowprops)disp = ax.annotate('display = (%.1f, %.1f)' % (xdisplay, ydisplay),(xdisplay, ydisplay), xytext=(0.5*offset, -offset), #xytext 好像是text離前面點的距離xycoords='figure pixels', #這個屬性來變換坐標系textcoords='offset points',bbox=bbox, arrowprops=arrowprops)plt.show()很顯然的一點是,當我們改變xlim, ylim的時候,同樣的數據點轉換成顯示窗口后發(fā)生變化
ax.transData.transform((5, 0)) array([221.4 , 144.72]) ax.set_ylim(-1, 2) (-1, 2) ax.transData.transform((5, 0)) array([221.4 , 108.48]) ax.set_xlim(10, 20) (10, 20) ax.transData.transform((5, 0)) array([-113.4 , 108.48])Axes coordinates
除了數據坐標系,Axes坐標系是第二常用的,就像在上表中提到的(0, 0)表示左下角,而(1, 1)表示右上角,(0.5, 0.5)則表示中心。我們也可以過分一點,使用(-0.1, 1.1)會顯示在axes的外圍左上角部分。
fig = plt.figure() for i, label in enumerate(('A', 'B', 'C', 'D')):ax = fig.add_subplot(2, 2, i+1)ax.text(0.05, 0.95, label, transform=ax.transAxes,fontsize=16, fontweight='bold', va='top')plt.show()從上面的例子中我們可以看到,想在多個axes中相同的位置放置相似的東西,用ax.transAxes時非常方便的
fig, ax = plt.subplots() x, y = 10*np.random.rand(2, 1000) ax.plot(x, y, 'go', alpha=0.2) # plot some data in data coordinatescirc = mpatches.Circle((0.5, 0.5), 0.25, transform=ax.transAxes,facecolor='blue', alpha=0.75) ax.add_patch(circ) plt.show()可以看到,上面的橢圓與數據坐標無關,始終放置在中間
Blended transformations 混合坐標系統(tǒng)
import matplotlib.transforms as transformsfig, ax = plt.subplots() x = np.random.randn(1000)ax.hist(x, 30) ax.set_title(r'$\sigma=1 \/ \dots \/ \sigma=2$', fontsize=16)# the x coords of this transformation are data, and the # y coord are axes trans = transforms.blended_transform_factory(ax.transData, ax.transAxes)# highlight the 1..2 stddev region with a span. # We want x to be in data coordinates and y to # span from 0..1 in axes coords rect = mpatches.Rectangle((1, 0), width=1, height=1,transform=trans, color='yellow',alpha=0.5)ax.add_patch(rect)plt.show()注意到,上面我們使用了混合坐標系統(tǒng),x軸方向是數據坐標系,而y軸方向是axes的坐標系統(tǒng),我們做一個反轉試試
import matplotlib.transforms as transformsfig, ax = plt.subplots() x = np.random.randn(1000)ax.hist(x, 30) ax.set_title(r'$\sigma=1 \/ \dots \/ \sigma=2$', fontsize=16)# the x coords of this transformation are data, and the # y coord are axes trans = transforms.blended_transform_factory(ax.transAxes, ax.transData) #調了一下# highlight the 1..2 stddev region with a span. # We want x to be in data coordinates and y to # span from 0..1 in axes coords rect = mpatches.Rectangle((0.5, 0), width=0.5, height=50, #注意這里的區(qū)別transform=trans, color='yellow',alpha=0.5)ax.add_patch(rect)plt.show()plotting in physical units
fig, ax = plt.subplots(figsize=(5, 4)) x, y = 10*np.random.rand(2, 1000) ax.plot(x, y*10., 'go', alpha=0.2) # plot some data in data coordinates # add a circle in fixed-units circ = mpatches.Circle((2.5, 2), 1.0, transform=fig.dpi_scale_trans,facecolor='blue', alpha=0.75) ax.add_patch(circ) plt.show()上面的圓使用了transform=fig.dpi_scale_trans坐標系統(tǒng),其圓心為(2.5, 2),半徑為1,顯然這些都是以figsize為基準的,所以,這個圓會在圖片中心,如果我們變換figsize,圖片的位置(顯示位置)會發(fā)生變化
fig, ax = plt.subplots(figsize=(7, 2)) x, y = 10*np.random.rand(2, 1000) ax.plot(x, y*10., 'go', alpha=0.2) # plot some data in data coordinates # add a circle in fixed-units circ = mpatches.Circle((2.5, 2), 1.0, transform=fig.dpi_scale_trans,facecolor='blue', alpha=0.75) ax.add_patch(circ) plt.show()再來看一個有趣的例子,雖然我不知道改如何解釋
fig, ax = plt.subplots() xdata, ydata = (0.2, 0.7), (0.5, 0.5) ax.plot(xdata, ydata, "o") ax.set_xlim((0, 1))trans = (fig.dpi_scale_trans +transforms.ScaledTranslation(xdata[0], ydata[0], ax.transData))# plot an ellipse around the point that is 150 x 130 points in diameter... circle = mpatches.Ellipse((0, 0), 150/72, 130/72, angle=40,fill=None, transform=trans) ax.add_patch(circle) plt.show()注意上面trans后面有個+號,這個表示,顯示用dpi_scale_trans,即在圖片(0, 0)也就是左下角位置畫一個大小合適的橢圓,然后將這個橢圓移動到(x[data][0], y[data][0])位置處,感覺實現是橢圓上點每個都加上(xdata[0], ydata[0])
使用offset transforms 創(chuàng)建陰影效果
fig, ax = plt.subplots()# make a simple sine wave x = np.arange(0., 2., 0.01) y = np.sin(2*np.pi*x) line, = ax.plot(x, y, lw=3, color='blue')# shift the object over 2 points, and down 2 points dx, dy = 2/72., -2/72. offset = transforms.ScaledTranslation(dx, dy, fig.dpi_scale_trans) shadow_transform = ax.transData + offset# now plot the same data with our offset transform; # use the zorder to make sure we are below the line ax.plot(x, y, lw=3, color='gray',transform=shadow_transform,zorder=0.5*line.get_zorder())ax.set_title('creating a shadow effect with an offset transform') plt.show()函數鏈接
matplotlib.transforms
inverted()-轉回來
ScaledTranslation
轉載于:https://www.cnblogs.com/MTandHJ/p/10957744.html
總結
以上是生活随笔為你收集整理的matplotlib 高阶之Transformations Tutorial的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Flask - app的配置和实例化Fl
- 下一篇: 冲刺阶段——Day5