如何使用 matplotlib 绘制具有长度颜色渐变的 3d 箭袋图?给出错误“ValueError:对象对于所需数组来说太深" [英] How to plot with matplotlib a 3d quiver plot with color gradient for length? gives error "ValueError: object too deep for desired array"

查看:24
本文介绍了如何使用 matplotlib 绘制具有长度颜色渐变的 3d 箭袋图?给出错误“ValueError:对象对于所需数组来说太深"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过颜色编码来指示箭袋的长度(箭头是否称为箭袋?).这对 2d 箭袋图没有问题.

def plot_3d_quiver(x, y, z, u, v, w):c = np.sqrt(np.abs(v) ** 2 + np.abs(u) ** 2 + np.abs(w) ** 2)c = (c.ravel() - c.min())/c.ptp()# 对每条身体线和两条头部线重复c = np.concatenate((c, np.repeat(c, 2)))# 颜色图c = plt.cm.jet(c)fig = plt.figure()ax = fig.gca(projection='3d')ax.quiver(x, y, z, u, v, w, 颜色=c, 长度=0.1)plt.show()

I want to indicate the length of the quivers (are the arrows calls quivers?) by color coding them. That is no issue with 2d quiver plots. Here it is done. With 3d projection it fails hard. This code reproduces the issue.

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.gca(projection='3d')

# Make the grid
x, y, z = np.meshgrid(np.arange(-0.8, 1, 0.2),
                      np.arange(-0.8, 1, 0.2),
                      np.arange(-0.8, 1, 0.8))

# Make the direction data for the arrows
u = np.sin(np.pi * x) * np.cos(np.pi * y) * np.cos(np.pi * z)
v = -np.cos(np.pi * x) * np.sin(np.pi * y) * np.cos(np.pi * z)
w = (np.sqrt(2.0 / 3.0) * np.cos(np.pi * x) * np.cos(np.pi * y) *
     np.sin(np.pi * z))
M = np.sqrt(u**2 + v**2 + w**2)
ax.quiver(x, y, z, u, v, w, M)

plt.show()

this produces a long traceback within a couple of matplotlib files and ends with

ValueError: object too deep for desired array

How can I avoid this issue and color-code my quivers?

解决方案

As @venky__ pointed out, there has been discussion about similar things before. I put that into a subroutine and adjusted for arrow length, even taking into account complex numbers in my arrays.

def plot_3d_quiver(x, y, z, u, v, w):
    c = np.sqrt(np.abs(v) ** 2 + np.abs(u) ** 2 + np.abs(w) ** 2)
    c = (c.ravel() - c.min()) / c.ptp()
    # Repeat for each body line and two head lines
    c = np.concatenate((c, np.repeat(c, 2)))
    # Colormap
    c = plt.cm.jet(c)

    fig = plt.figure()
    ax = fig.gca(projection='3d')
    ax.quiver(x, y, z, u, v, w, colors=c, length=0.1)
    plt.show()

这篇关于如何使用 matplotlib 绘制具有长度颜色渐变的 3d 箭袋图?给出错误“ValueError:对象对于所需数组来说太深"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆