[英]How to add a projection to axis in matplotlib when using subplot2grid?
[英]How do I change matplotlib's subplot projection of an existing axis?
我正在嘗試構建一個簡單的函數,該函數采用子圖實例( matplotlib.axes._subplots.AxesSubplot
)並將其投影轉換為另一個投影,例如,轉換為cartopy.crs.CRS
投影之一。
這個想法看起來像這樣
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
def make_ax_map(ax, projection=ccrs.PlateCarree()):
# set ax projection to the specified projection
...
# other fancy formatting
ax2.coastlines()
...
# Create a grid of plots
fig, (ax1, ax2) = plt.subplots(ncols=2)
# the first subplot remains unchanged
ax1.plot(np.random.rand(10))
# the second one gets another projection
make_ax_map(ax2)
當然,我可以只使用fig.add_subplot()
函數:
fig = plt.figure(figsize=(10,5))
ax1 = fig.add_subplot(121)
ax1.plot(np.random.rand(10))
ax2 = fig.add_subplot(122,projection=ccrs.PlateCarree())
ax2.coastlines()
但我想知道是否有合適的matplotlib
方法在定義后更改子圖軸投影。 不幸的是,閱讀 matplotlib API 並沒有幫助。
您無法更改現有軸的投影,原因如下。 然而,解決你的根本問題是,僅僅使用subplot_kw
參數plt.subplots()
的matplotlib文檔中描述這里。 例如,如果您希望所有子圖都具有cartopy.crs.PlateCarree
投影,則可以執行
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
# Create a grid of plots
fig, (ax1, ax2) = plt.subplots(ncols=2, subplot_kw={'projection': ccrs.PlateCarree()})
關於實際問題,在創建軸集時指定投影決定了您獲得的軸類,每種投影類型都不同。 例如
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
ax1 = plt.subplot(311)
ax2 = plt.subplot(312, projection='polar')
ax3 = plt.subplot(313, projection=ccrs.PlateCarree())
print(type(ax1))
print(type(ax2))
print(type(ax3))
此代碼將打印以下內容
<class 'matplotlib.axes._subplots.AxesSubplot'>
<class 'matplotlib.axes._subplots.PolarAxesSubplot'>
<class 'cartopy.mpl.geoaxes.GeoAxesSubplot'>
注意每個軸實際上是不同類的實例。
假設有多個軸用於 2D 繪圖,例如...
fig = matplotlib.pyplot.Figure()
axs = fig.subplots(3, 4) # prepare for multiple subplots
# (some plotting here)
axs[0,0].plot([1,2,3])
...人們可以簡單地摧毀其中一個並用具有 3D 投影的新的替換它:
axs[2,3].remove()
ax = fig.add_subplot(3, 4, 12, projection='3d')
ax.plot_surface(...)
請注意,與 Python 的其余部分不同, add_subplot
使用從 1 (而不是從 0)開始的行列索引。
編輯:改變了我關於索引的錯字。
按照這個問題的答案:
我發現了一個在創建斧頭后改變它的投影的技巧,這似乎至少在下面的簡單示例中有效,但我不知道這個解決方案是否是最好的方法
from matplotlib.axes import Axes
from matplotlib.projections import register_projection
class CustomAxe(Axes):
name = 'customaxe'
def plotko(self, x):
self.plot(x, 'ko')
self.set_title('CustomAxe')
register_projection(CustomAxe)
if __name__ == '__main__':
import matplotlib.pyplot as plt
fig = plt.figure()
## use this syntax to create a customaxe directly
# ax = fig.add_subplot(111, projection="customaxe")
## change the projection after creation
ax = plt.gca()
ax.__class__ = CustomAxe
ax.plotko(range(10))
plt.show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.