Python:在 3d 绘图的 x-y 平面上绘制底图

问题描述 投票:0回答:1

我正在尝试获取

中包含的代码

https://basemaptutorial.readthedocs.io/en/latest/basemap3d.html

去工作。但是,我在第一个片段中已经收到错误:

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

map = Basemap()

fig = plt.figure()
ax = Axes3D(fig)

'''
ax.azim = 270
ax.elev = 90
ax.dist = 5
'''

ax.add_collection3d(map.drawcoastlines(linewidth=0.25))
ax.add_collection3d(map.drawcountries(linewidth=0.35))

plt.show()

错误内容为:

Traceback (most recent call last):
  File ".../main.py", line 16, in <module>
    ax.add_collection3d(map.drawcoastlines(linewidth=0.25))
  File ".../venv/lib/python3.12/site-packages/mpl_toolkits/mplot3d/axes3d.py", line 2314, in add_collection3d
    collection = super().add_collection(col)
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File ".../venv/lib/python3.12/site-packages/matplotlib/axes/_base.py", line 2260, in add_collection
    self._set_artist_props(collection)
  File ".../venv/lib/python3.12/site-packages/matplotlib/axes/_base.py", line 1177, in _set_artist_props
    a.axes = self
    ^^^^^^
  File ".../venv/lib/python3.12/site-packages/matplotlib/artist.py", line 302, in axes
    raise ValueError("Can not reset the axes.  You are probably "
ValueError: Can not reset the axes.  You are probably trying to re-use an artist in more than one Axes which is not supported

Process finished with exit code 1

我还找不到解决方案。我的最终目标是实现类似于用户 guidocioni 在此显示的内容:https://community.plotly.com/t/adding-a-world-map-to-a-3d-volume-graph-python/33592/ 2

python matplotlib 3d matplotlib-basemap
1个回答
0
投票

drawcoastlines
创建一个 Matplotlib
LineCollection
并在返回之前将其添加到 2D 轴。 现代 Matplotlib 不允许您将同一艺术家添加到两个轴。 我们可以直接从 LineCollection
 属性创建 
coastsegs
 并将其添加到 3D 轴。  
drawcountries
 类似,只不过它
调用私有方法来确保 cntrysegs
 属性存在
。 因此,作为解决方法,我首先将国家/地区添加到二维图中,然后将其丢弃。

import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap from matplotlib.collections import LineCollection map = Basemap() # Draw and discard a dummy 2D plot so that country data is added as the # cntrysegs attribute. fig, dummy_ax = plt.subplots() map.drawcountries(ax=dummy_ax) plt.close(fig) # Create the figure and 3D axes we are actually going to use. fig = plt.figure() ax = fig.add_subplot(projection='3d') # Create and add boundary LineCollections. coastlines = LineCollection(map.coastsegs, linewidth=0.25, color='black') countries = LineCollection(map.cntrysegs, linewidth=0.35, color='black') ax.add_collection3d(coastlines) ax.add_collection3d(countries) # Set global x and y limits. ax.set_xlim(-180, 180) ax.set_ylim(-90, 90) plt.show()

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.