在matplotlib.mplot3d立方体上绘制底图

3 投票
2 回答
2069 浏览
提问于 2025-04-16 18:30

正如标题所说,我想在matplotlib.mplot3d的线图中,把Basemap地图绘制在z=0的表面上。我知道Axes3D对象可以在z=0的表面上绘图(通过Axes3D.plot、Axes3D.scatter等方法),但我不知道怎么用Basemap对象来做到这一点。希望下面的代码能清楚地展示我需要的内容。任何建议都非常感谢!

import matplotlib.pyplot as pp
from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.basemap import Basemap

# make sample data for 3D lineplot
z = np.linspace(-2, 2, 100)
r = z**2 + 1
x = r * np.sin(theta)
y = r * np.cos(theta)

# make the 3D line plot
FIG = ct.pp.figure()
AX = Axes3D(FIG)
AX.plot(x, y, z, '-b')

# make the 2D basemap
### NEEDS TO SOMEHOW BE AT z=0 IN FIG
M = ct.Basemap(projection='stere', width=3700e3, height=2440e3,
               lon_0=-5.0, lat_0=71.0, lat_ts=71.0,
               area_thresh=100, resolution='c')
PATCHES = M.fillcontinents(lake_color='#888888', color='#282828')

2 个回答

-2

AX.add_collection3d(M.drawcoastlines())

这个代码可以正常运行,但

PATCHES = M.fillcontinents(lake_color='#888888', color='#282828')

这个代码就不行了。

一旦你尝试添加颜色填充,就会出现一个错误,类似于:“AttributeError: 'Polygon' object has no attribute 'do_3d_projection'”。

M.fillcontinents(lake_color='#888888', color='#282828')`

这个错误的原因是它返回的是一个多边形的数组,而不是 add_collection() 所需要的输入。collect.PatchCollection() 似乎也不管用。

那么,怎么才能把 `M.fillcontinents(lake_color='#888888', color='#282828')` 加入到一个3D图中呢?

1

只需要把你的地图作为一个三维集合添加到 Axes3D 实例中就可以了:

import numpy as np
import matplotlib.pyplot as pp
from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.basemap import Basemap

theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)
z = np.linspace(-500, 500, 100)
r = z**2 + 1
x = r * np.sin(theta)
y = r * np.cos(theta)

FIG = pp.figure()
AX = Axes3D(FIG)
AX.plot(x, y, z, '-b')

M = Basemap(projection='stere', width=3700e3, height=2440e3,
               lon_0=-5.0, lat_0=71.0, lat_ts=71.0,
               area_thresh=100, resolution='c')
AX.add_collection3d(M.drawcoastlines())
AX.grid(True)

pp.draw()
pp.show()

撰写回答