【问题标题】:Plot stack of unit vectors in cylindrical coordinates - matplotlib在柱坐标中绘制单位向量的堆栈 - matplotlib
【发布时间】:2014-01-17 16:15:38
【问题描述】:

我有一个 python 程序,它可以为我计算角度并将它们输出到一个列表中。

我想做的是绘制一堆箭头,这些箭头是指向角度方向的单位向量。所以我认为柱坐标最好,因为它们只有一个角坐标。

我尝试过 pyplot.quiver,但我不认为它可以在 3D 中做任何事情,而且 3D 线图也不起作用。

有没有一种方法可以不用费力地将每个 (length, height, angle) 转换成一对向量 (a, b, c),(length*cos(angle), length*sin(angle), height )?

【问题讨论】:

    标签: python 3d matplotlib


    【解决方案1】:

    如果您有角度列表,则可以使用 numpy 轻松计算与这些角度相关的向量。

    import numpy as np
    import matplotlib.pyplot as plt
    angles = np.random.rand(100)
    
    length = 1.
    vectors_2d = np.vstack((length * np.cos(angles), length * np.sin(angles))).T
    
    for x, y in vectors_2d:
        plt.plot([0, x], [0, y])
    plt.show()
    


    如果你真的想要圆柱而不是极坐标,那么

    import numpy as np
    import matplotlib.pyplot as plt
    from mpl_toolkits.mplot3d import Axes3D
    angles = np.random.rand(100)
    
    length = 1.
    heights = np.arange(len(angles))
    vectors_3d = np.vstack((length * np.cos(angles), 
                            length * np.sin(angles), 
                            heights)).T
    
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    for x, y, z in vectors_3d:
        ax.plot([0, x], [0, y], zs=[z, z])
    plt.show()
    


    编辑:我知道如何使用pyplot.quiver 在绘图上放置箭头。然而,我不认为mplot3dquiver 配合得很好。也许像@tcaswell 这样的人可以帮助解决问题。但在 2D 中,你可以这样做

    import numpy as np
    import matplotlib.pyplot as plt
    
    angles = np.random.rand(100)
    # Define coords for arrow tails (the origin)
    x0, y0 = np.zeros(100), np.zeros(100)
    # Define coords for arrow tips (cos/sin)
    x, y = np.cos(angles), np.sin(angles)
    
    # in case you want colored arrows
    colors = 'bgrcmyk'
    colors *= colors * (len(x0) / len(colors) + 1)
    plt.quiver(x0, y0, x, y, color=colors[:len(x0)], scale=1) #scale sets the length
    plt.show()
    

    【讨论】:

    • 太棒了,非常感谢。你知道如何在行尾添加箭头吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 2014-02-26
    • 2017-05-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多