Matplotlib - 单个箭头的单独颜色

时间:2015-01-22 09:58:44

标签: python matplotlib colors arrows

我正在创建一系列xyz箭头并生成一系列图片。怎么做一个红色,一个蓝色和另一个绿色?

我使用的代码如下。

import numpy as np
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.patches import FancyArrowPatch
from mpl_toolkits.mplot3d import proj3d

class Arrow3D(FancyArrowPatch):
    def __init__(self, xs, ys, zs, *args, **kwargs):
        FancyArrowPatch.__init__(self, (0,0), (0,0), *args, **kwargs)
        self._verts3d = xs, ys, zs

    def draw(self, renderer):
        xs3d, ys3d, zs3d = self._verts3d
        xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)
        self.set_positions((xs[0],ys[0]),(xs[1],ys[1]))
        FancyArrowPatch.draw(self, renderer)

mu_vec1 = np.array([0,0,0])
cov_mat1 = np.array([[1,0,0],[0,1,0],[0,0,1]])
class1_sample = np.random.multivariate_normal(mu_vec1, cov_mat1, 20)

eig_val, eig_vec = np.linalg.eig(cov_mat1)   

fig = plt.figure(figsize=(10,10))
ax = fig.add_subplot(111, projection='3d', axisbg='black')

for v in eig_vec.T:
    a = Arrow3D([0, v[0]], [0, v[1]], 
                [0, v[2]], mutation_scale=20, lw=5, arrowstyle="-|>", color='red')
    ax.add_artist(a)
ax.axis('off')

plt.show()

1 个答案:

答案 0 :(得分:0)

首先,您要创建颜色列表colors,然后使用for将列表添加到itertools.izip循环中。 这对我有用:

import numpy as np
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.patches import FancyArrowPatch
from mpl_toolkits.mplot3d import proj3d
import itertools

class Arrow3D(FancyArrowPatch):
    def __init__(self, xs, ys, zs, *args, **kwargs):
        FancyArrowPatch.__init__(self, (0,0), (0,0), *args, **kwargs)
        self._verts3d = xs, ys, zs

    def draw(self, renderer):
        xs3d, ys3d, zs3d = self._verts3d
        xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)
        self.set_positions((xs[0],ys[0]),(xs[1],ys[1]))
        FancyArrowPatch.draw(self, renderer)

mu_vec1 = np.array([0,0,0])
cov_mat1 = np.array([[1,0,0],[0,1,0],[0,0,1]])
class1_sample = np.random.multivariate_normal(mu_vec1, cov_mat1, 20)

eig_val, eig_vec = np.linalg.eig(cov_mat1)   

fig = plt.figure(figsize=(10,10))
ax = fig.add_subplot(111, projection='3d', axisbg='black')

colors = ['red','blue','green']

for v,c in itertools.izip(eig_vec.T,colors):
    a = Arrow3D([0, v[0]], [0, v[1]], 
                [0, v[2]], mutation_scale=20, lw=5, arrowstyle="-|>", color=c)
    ax.add_artist(a)
ax.axis('off')

plt.show()