我试图构造一个简单的函数,该函数接受子图实例(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没有帮助。
发布于 2016-01-04 15:37:53
您不能更改现有轴的投影,原因如下。但是,您的根本问题的解决方案只是使用matplotlib文档中描述的subplot_kw
参数到plt.subplots()
。例如,如果您希望所有的子图都具有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()})
对于实际的问题,在创建一个轴集时指定一个投影将决定您得到的axes类,这对于每种投影类型都是不同的。例如
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'>
注意每个轴实际上是一个不同类的实例。
发布于 2020-09-13 20:38:18
假设有多个轴被用于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开始)启动。
编辑:更改了我关于索引的错误。
发布于 2019-05-22 07:22:31
以下是对这个问题的答复:
在创建斧头之后,我发现了一种改变斧头投影的方法,这似乎至少在下面的简单示例中有效,但我不知道这个解决方案是否是最好的方法。
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()
https://stackoverflow.com/questions/33942233
复制相似问题