How can emulate transform_vector of basemap in cartopy

大憨熊 提交于 2021-02-10 17:34:25

问题


I want to utilize basemap's transform_vector function and its ability to return x and y, in cartopy to plot barbs

This is the code in basemap

u1, v1, x1, y1 = bm.transform_vector(u, v, self.lons, self.lats, 16, 16, 
                                     returnxy=True)

bm.barbs(x1, y1, u1, v1,
         barbcolor='firebrick', flagcolor='firebrick', pivot='middle',
         linewidths=1)

I want to achieve this in cartopy but transform_vectors in cartopy does not have option to returnxy, so how can I do this? Assume we already have u, v, self.lons and self.lats


回答1:


Since Cartopy does not provide single step to meet your requirement, you have to create a function that combines the required operations within it. Here I offer a working code that does what you need. Look for the function vectrans() inside the code.

import matplotlib.pyplot as plt
import cartopy
import cartopy.crs as ccrs
import numpy as np

num = 12   # number of points to plot for demo
scale = 7  # scale to get proper sizes of barbs
# generate (u,v) vector components
us, vs = (np.random.random([num])-0.5)*scale, (np.random.random([num])-0.5)*scale
# generate (lons,lats) accompanying the vectors
lons = np.linspace(-120, 170, num)
lats = np.ones(num)*40
# create source and target projections
srcProj = ccrs.PlateCarree()  # basic values: long, lat (equivalent)
tgtProj = ccrs.Robinson()

# here is a function to emulate `transform_vector`
def vectrans(u, v, lons, lats):
    u_tgt, v_tgt = tgtProj.transform_vectors(srcProj, lons, lats, u, v)
    xyz = tgtProj.transform_points(srcProj, lons, lats)
    x_tgt = xyz[:,0]
    y_tgt = xyz[:,1]
    return x_tgt, y_tgt, u_tgt, v_tgt

# setup fig/axis and plot the meshgrid of points
fig = plt.figure()
ax = fig.add_axes([0, 0, 1, 1], projection=tgtProj)
ax.add_feature(cartopy.feature.LAND, facecolor='lightgray')

# use vectrans() to get values for barbs plotting
tgt_x, tgt_y, u_tgt, v_tgt = vectrans(us, vs, lons, lats)

# plot points and barbs
ax.scatter(tgt_x, tgt_y, s=7, c="k", zorder=10)
ax.barbs(tgt_x, tgt_y, u_tgt, v_tgt, barbcolor='firebrick', flagcolor='firebrick', pivot='middle',
         linewidths=1, zorder=11)
ax.set_global()
plt.show()



来源:https://stackoverflow.com/questions/56689199/how-can-emulate-transform-vector-of-basemap-in-cartopy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!