我不确定如何在 Python 中从 shapefile 中绘制虚线。 readshapefile() 似乎没有任何线型供我设置。下面我有一个工作代码,我在其中获取一个 shapefile 并绘制它,但它只绘制一条实线。有什么想法可以让我朝着正确的方向前进吗?谢谢!
shapefile 可以在这里找到:http://www.natice.noaa.gov/products/daily_products.html ,其中开始日期为 2 月 15 日,结束日期为 2 月 17 日,日期类型为 Ice Edge。它应该是第一个链接。
#!/awips2/python/bin/python
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
map = Basemap(llcrnrlon=-84.37,llcrnrlat=42.11,urcrnrlon=-20.93,urcrnrlat=66.48,
resolution='i', projection='tmerc', lat_0 = 55., lon_0 = -50.)
map.drawmapboundary(fill_color='aqua')
map.fillcontinents(color='#ddaa66',lake_color='aqua')
map.drawcoastlines(zorder = 3)
map.readshapefile('nic_autoc2018046n_pl_a', 'IceEdge', zorder = 2, color = 'blue')
plt.show()
请您参考如下方法:
来自 basemap 文档:
A tuple (num_shapes, type, min, max) containing shape file info is returned. num_shapes is the number of shapes, type is the type code (one of the SHPT* constants defined in the shapelib module, see http://shapelib.maptools.org/shp_api.html) and min and max are 4-element lists with the minimum and maximum values of the vertices. If drawbounds=True a matplotlib.patches.LineCollection object is appended to the tuple.
drawbounds 默认为 True,因此您只需收集 readshapefile 的返回值并更改 linestyle返回的 ,这可以通过 LineCollection 对象的 LineCollection.set_linestyle() 完成。所以原则上你可以用这样的东西改变你绘制的形状文件的线型:
result = m.readshapefile('shapefiles/nic_autoc2018046n_pl_a', 'IceEdge', zorder = 10, color = 'blue')#, drawbounds = False)
col = result[-1]
col.set_linestyle('dotted')
plt.show()
但是,您的 shapefile 包含 5429 个不同长度的独立线段,而 matplotlib 似乎无法以某种方式处理如此大量的非连续线。至少在我的机器上绘图没有在一小时内完成,所以我中断了这个过程。我玩了一下你的文件,似乎很多线都被不必要地分成几段(我猜这是因为冰原轮廓是在瓷砖上以某种方式确定的,然后拼凑在一起,但只有提供者才真正知道).也许将相邻的部分拼凑起来会有所帮助,但我不确定。
我还想知道结果是否会用虚线看起来那么好,因为有很多急转弯。下面我展示了一张图片,其中我使用以下代码仅绘制了 100 个最长 线段(省略了 drawcoaSTLines 并使用了较粗的线):
import numpy as np
result = m.readshapefile('shapefiles/nic_autoc2018046n_pl_a', 'IceEdge', zorder = 10, color = 'blue')#, drawbounds = False)
col = result[-1]
segments = col.get_segments()
seglens = [len(seg) for seg in col.get_segments()]
segments = np.array(segments)
seglens = np.array(seglens)
idx = np.argsort(seglens)
seglens = seglens[idx]
segments = segments[idx]
col.remove()
new_col = LineCollection(segments[-100:],linewidths = 2, linestyles='dotted', colors='b')
ax.add_collection(new_col)
plt.show()
结果是这样的:
