如何使用matplot3d更改3d点的形状/颜色

时间:2013-04-28 16:38:43

标签: python python-2.7 matplotlib plot

Python和MatPlot3D新手。我有一个情节,我希望根据某些属性使用不同的形状和颜色显示坐标。数据看起来像这样。

col1 col2   col3 col4 col5
276  147    -6   K  dia
274  145    -8   A  cir
270  141    -12  B  dia
267  138    -15  K  cir
266  137    -16  K  cir
261  132    -21  B  bu
251  122    -31  C  cir

现在我想基于col4和基于col5的形状颜色更改形状。我现在有这个代码从文件读取数据点,只绘制点。

from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import matplotlib.pyplot as plt
from matplotlib.mlab import griddata
import numpy as np

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

data = np.genfromtxt('distances.txt')

x = data[:,0]
y = data[:,1]
z = data[:,3]

ax.scatter(x, y, z,c='red',marker='^')

ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')

plt.show()

如何根据col4和col5的值轻松指定形状和颜色?

1 个答案:

答案 0 :(得分:1)

您需要做的第一件事是以不将这些列转换为“nan”的方式导入数据,然后需要将列值转换为mpl可以理解的值。

from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import matplotlib.pyplot as plt
from matplotlib.mlab import griddata
import numpy as np
import csv

color_map = {'A':'r', 'B':'b', 'K':'k', 'C':'c'}
shape_map = {'dia':'^', 'cir':'o', 'bu':'.'}

with open('/tmp/dist.txt','r') as in_file:
    reader = csv.DictReader(in_file, delimiter=' ', skipinitialspace=True)
    data = []
    for r in reader:
        data.append([float(r['col1']),
                     float(r['col2']),
                     float(r['col3']),
                     color_map[r['col4']],
                     shape_map[r['col5']]])

为了获得颜色很容易,scatter将为每个标记着色采用可迭代的颜色:

X, Y, Z, col, shape = zip(*data)


fig = plt.figure()
ax = fig.add_subplot(111,projection='3d')
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')


ax.scatter(X, Y, Z, c=col)

获取形状有点棘手,因为scatter只需要一个marker所有点,所以如果你想使用多个scatter来电:

import collections

by_shape = collections.defaultdict(list)
for d in data:
    by_shape[d[4]].append(d[:4])

for key, val in by_shape.items():
    X, Y, Z, col = zip(*val)
    ax.scatter(X, Y, Z, c=col, marker=key)