带有彩色箭袋的色彩图

Yor*_*ian 5 python matplotlib matplotlib-basemap

我正在绘制一张地图,上面有箭头。这些箭头代表风向、平均风速(每个方向)和发生情况(每个方向)。

方向由箭头的方向指示。箭头的长度表示该方向的平均风速。箭头的颜色表示该方向有风。

这一切都可以与下面的脚本配合使用:

windData = pd.read_csv(src+'.txt'), sep='\t', names=['lat', 'lon', 'wind_dir_start', 'wind_dir_end', 'total_num_data_points','num_data_points', 'avg_windspeed']).dropna()

# plot map
m = Basemap(llcrnrlon=minLon, llcrnrlat=minLat, urcrnrlon=maxLon, urcrnrlat=maxLat, resolution='i')
Left, Bottom = m(minLon, minLat)
Right, Top = m(maxLon, maxLat)

# get x y
x, y = m(windData['lon'], windData['lat'])

# angles
angleStart = -windData['wind_start']+90
angleStart[angleStart<0] = np.radians(angleStart[angleStart<0]+360.)

angleEnd = -windData['wind_end']+90
angleEnd[angleEnd<0] = np.radians(angleEnd[angleEnd<0]+360.)

angle = angleStart + math.radians(binSize/2.)

xux = np.cos(angle) * windData['avg_windspeed']
yuy = np.sin(angle) * windData['avg_windspeed']

# occurence
occurence = (windData['num_data_points']/windData['total_num_data_points'])

xi = np.linspace(minLon, maxLon, 300)
yi = np.linspace(minLat, maxLat, 300)

# plotting
## xux and yuy are used negatively because they are measured as "coming from" and displayed as "going to"
# To make things more readable I left a threshold for the occurence out
# I usually plot x, y, xux, yuy and the colors as var[occurence>threshold]
Q = m.quiver(x, y, -xux, -yuy, scale=75, zorder=6, color=cm.jet, width=0.0003*Width, cmap=cm.jet)
qk = plt.quiverkey(Q, 0.5, 0.92, 3, r'$3 \frac{m}{s}$', labelpos='S', fontproperties={'weight': 'bold'})
m.scatter(x, y, c='k', s=20*np.ones(len(x)), zorder=10, vmin=4.5, vmax=39.)
Run Code Online (Sandbox Code Playgroud)

该图很好地显示了箭头,但现在我想添加一个颜色图,指示该图旁边出现的百分比。我该怎么做?

gbo*_*ffi 6

好的

通常进口,加上import matplotlib

%matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
Run Code Online (Sandbox Code Playgroud)

伪造要绘制的数据(MCVE 的 tx)

NP = 10
np.random.seed(1)
x = np.random.random(NP)
y = np.random.random(NP)
angle = 1.07+np.random.random(NP) # NE to NW
velocity = 1.50+np.random.random(NP)
o = np.random.random(NP)
occurrence = o/np.sum(o)
dx = np.cos(angle)*velocity
dy = np.sin(angle)*velocity
Run Code Online (Sandbox Code Playgroud)

创建一个可映射的对象,以便 Matplotib 没有理由抱怨“运行时错误:找不到可用于创建颜色条的可映射对象”。

norm = matplotlib.colors.Normalize()
norm.autoscale(occurrence)
cm = matplotlib.cm.copper

sm = matplotlib.cm.ScalarMappable(cmap=cm, norm=norm)
sm.set_array([])
Run Code Online (Sandbox Code Playgroud)

并绘制数据

plt.quiver(x, y, dx, dy, color=cm(norm(o)))
plt.colorbar(sm)
plt.show()
Run Code Online (Sandbox Code Playgroud)

颤动图暨颜色条

参考:

  1. matplotlib 散点图中的对数颜色条

  2. 使用 Matplotlib 在线图旁边绘制颜色条

  3. 箭袋图中箭头的不同颜色


PS 最近(肯定是在 3.+ 中)Matplotlib 发布了cm.set_array咒语不再需要


ml4*_*294 1

您想要颜色条显示不同的风速吗?如果是这样,将其放置在和plt.colorbar()之间就足够了。Q = m.quiver(...)qk = ...