在matplotlib上绘制定性数据

时间:2012-11-22 06:59:12

标签: python numpy matplotlib

我有三个相同长度的1D数组。这些是:

  1. 温度(F)
  2. 风速
  3. 风向
  4. 温度和风速都有浮动值,而风向有“南”,“北”,“东北”,“西”等字符串值。现在,我想用这些数组创建一个三维散点图。可能的方法是什么(因为风向阵列有字符串值)?某些逻辑可以应用于这种情况吗?

3 个答案:

答案 0 :(得分:4)

你可以定义一个字典角度来定义x轴(东方向)和风向之间的角度,如:

angles = {'East': 0., 'North': math.pi/2., 'West': math.pi, 'South': 3.*math.pi/2.}

然后您可以计算x(东)和y(北)方向的速度,如下例所示:

import math

angles = {'East': 0., 'North': math.pi/2., 'West': math.pi, 'South': 3.*math.pi/2.}

directions = ['East', 'North', 'West', 'South']
vtot = [1.5, 2., 0.5, 3.]
Temperature = [230., 250. , 200., 198.] # K

vx = [vtot[i]*math.cos(angles[directions[i]]) for i in range(len(directions))] # velocity in x-direction (East)
vy = [vtot[i]*math.sin(angles[directions[i]]) for i in range(len(directions))] # velocity in y-direction (North)

print (vx)
print (vy)

然后,您可以在matplotlib的任何3D图中绘制vxvyTemperature

答案 1 :(得分:2)

就像@pwagner一样,我会选择极地情节,但对于3D情节。基本上你可以做的是将你的风重新映射到极地度,如下例所示:

angles = {'east':0, 'northeast':np.pi/4, 'north':np.pi/2, 'northwest':3*np.pi/4,
          'west':np.pi, 'southwest':5*np.pi/4, 'south':3*np.pi/2, 'southeast':7*np.pi/4}
wind_angle = np.array([angles[i] for i in wind])

这会给你风向;然后你可以将你的(风,速度)坐标变换为笛卡尔坐标并通过3D散射绘制它。您甚至可以在colormap中编码温度,完整示例如下所示:

import numpy as np
from matplotlib import cm
from matplotlib import pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

wind_dirs = ['east', 'northeast', 'north', 'northwest',
             'west', 'southwest', 'south', 'southeast']
# data
speed = np.random.uniform(0,1.25,100)
temp = np.random.uniform(-10,20,100)
wind = [wind_dirs[i] for i in np.random.randint(8, size=100)]

#transform data to cartesian
angles = {'east':0, 'northeast':np.pi/4, 'north':np.pi/2, 'northwest':3*np.pi/4,
          'west':np.pi, 'southwest':5*np.pi/4, 'south':3*np.pi/2, 'southeast':7*np.pi/4}
wind_angle = np.array([angles[i] for i in wind])
X,Y = speed*np.cos(wind_angle),speed*np.sin(wind_angle)

ax.scatter3D(X, Y, temp, c = temp, cmap=cm.bwr)
ax.set_zlabel('Temp')
plt.show()

会生成一个漂亮的图形,可以旋转和缩放:

enter image description here

答案 2 :(得分:0)

当我正在阅读这个问题时,我必须想到一个极地情节(自然是风向)和温度编码为颜色。快速搜索提出了现有的matplotlib example。 重写示例,它可能如下所示:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm

N = 150
r = 2.0 * np.random.randn(N)
theta = 2.0 * np.pi * np.random.randn(N)
area = 10.0 * r**2.0 * np.random.randn(N)
colors = theta
ax = plt.subplot(111, polar=True)
c = plt.scatter(theta, r, c=colors, cmap=cm.hsv)
c.set_alpha(0.75)

ticklocs = ax.xaxis.get_ticklocs()
ax.xaxis.set_ticklabels([chr(number + 65) for number in range(len(ticklocs))])

plt.show()

我希望你能进一步根据自己的需要采用这个例子。