【问题标题】:Plotting epicycles by using matplotlib使用 matplotlib 绘制本轮
【发布时间】:2021-11-02 01:41:06
【问题描述】:

为什么下面的代码不起作用?

我想使用 matplotlib 来显示本轮,如下图所示

import matplotlib.pyplot as plt
import numpy as np
from numpy import *
import math


freqList = [1,2,3]
ampList = [1,2,4]
phaseList = [0,10,20]

circles = [] #create list of circles

x = 0
y = 0
for i in range(len(freqList)):
   prevx = x
   prevy = y
   theta = np.linspace( 0 , 2 * np.pi , 150 )
   x += ampList[i] * np.cos( theta*freqList[i] + phaseList[i] )
   y += ampList[i] * np.sin( theta*freqList[i] + phaseList[i] )

   circle = plt.Circle((prevx, prevy), ampList[i], fill=False)
   circles.append(circle)

   plt.figure()
   fig, ax = plt.subplots()
   ax.add_patch(circles[i])
   plt.axis("equal")
   plt.xlim( -10 , 10 ) 
   plt.ylim( -10 , 10 ) 
   plt.show()

提前感谢任何能给我一些想法的人!

【问题讨论】:

    标签: python numpy matplotlib plot visualization


    【解决方案1】:

    我对您的代码进行了一些更改:

    • 使用for i in range(len(list_name)) 循环列表的元素,然后使用list_name[i] 获取第ith 元素可以工作,但这有点尴尬;在 python 中,您可以直接遍历列表的元素:for element in list。如果需要遍历多个列表的元素,可以使用zip:for a, b in zip(list_a, list_b)

    • 在您的循环中,您一次生成一个圆圈,并将其添加到绘图中。只创建一次(不是每个循环一次)的东西必须在 for 循环之外生成; figax 等就是这种情况。

    • 在您的代码中,您创建了一个数组theta,它包含 150 个元素。在 for 循环中,您将 theta 的函数(也是一个数组)添加到 xy。所以,在第一次迭代中xyint 并表示第一个圆的坐标,然后它们就变成了数组。这就是你的代码抛出错误的原因

    • 如果你使用matplotlib.patches.Circle,你只需要中心坐标和半径。无需计算θ,无需使用freqList(如果我解释正确的话)。因此,在循环内部,您只需将当前中心坐标和半径传递给matplotlib.patches.Circle,并仅使用当前幅度和相位计算下一个圆的中心坐标

    话虽如此,您的代码变为:

    # import
    import matplotlib.pyplot as plt
    import numpy as np
    
    # amplitude and phase definition
    ampList = [1,2,4]
    phaseList = [0,10,20]
    
    # center coordinates of the first circle
    C_x = 0
    C_y = 0
    
    # generate figure and axis
    fig, ax = plt.subplots()
    
    # loop over each amplitude and phase
    for amp, phase in zip(ampList, phaseList):
    
        # draw current circle
        circle = plt.Circle((C_x, C_y), amp, fill = False)
        ax.add_patch(circle)
        # draw current circle center
        ax.plot(C_x, C_y, marker = 'o', markerfacecolor = 'k', markeredgecolor = 'k')
    
        # compute next circle center 
        C_x += amp*np.cos(np.deg2rad(phase))
        C_y += amp*np.sin(np.deg2rad(phase))
    
    # adjust axis
    plt.axis("equal")
    plt.xlim( -10 , 10 )
    plt.ylim( -10 , 10 )
    
    # show the plot
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-19
      • 2013-09-19
      相关资源
      最近更新 更多