简体   繁体   English

在Python中用变量Theta绘制函数

[英]Plot a Function with Variable Theta in Python

I'm new to Python, and especially new to plotting graphs using matplotlib. 我是Python的新手,尤其是使用matplotlib绘制图形的新手。 I'm working on an assignment where we have to plot spirographs on a cartesian coordinate system with equations for x and y: 我正在做一个作业,我们必须在笛卡尔坐标系上用x和y的方程式绘制呼吸描记器:

x = (R + r) * math.cos(theta) - d * math.cos((R+r)*theta/r)
y = (R + r) * math.sin(theta) - d * math.sin((R+r)*theta/r)

where we are given the values of R, r, and d. 给出R,r和d的值。

This produces an error because the variable theta isn't defined. 由于未定义变量theta,因此会产生错误。 I've seen ways of defining theta using numPy, but we aren't allowed to use that particular library for this assignment. 我已经看到了使用numPy定义theta的方法,但是我们不允许将此特定库用于此分配。 What would be the best way of plotting the spirographs for 0 < theta < 2pi? 绘制0 <theta <2pi的呼吸描记器的最佳方法是什么?

Thanks in advance! 提前致谢!

If you cannot use numpy, you cannot use matplotlib; 如果不能使用numpy,则不能使用matplotlib;否则,不能使用matplotlib。 because numpy is a dependency of matplotlib. 因为numpy是matplotlib的依赖项。 So I'd suggest to solve your problem in the following way: 因此,我建议您通过以下方式解决您的问题:

Prepend a sentence to your solution saying "Because numpy is a dependency of matplotlib, it's technically impossible to solve this task without using numpy. Since I do not want this restriction to prevent me from solving the task, I simply assume that I can use numpy here." 在您的解决方案前面加上一句话:“由于numpy是matplotlib的依赖项,因此在不使用numpy的情况下解决此任务在技术上是不可能的。由于我不想让此限制阻止我解决该任务,因此我只是假设我可以使用numpy这里。”

Then go on with the canonical solution, 然后继续规范的解决方案,

import matplotlib.pyplot as plt
import numpy as np

theta = np.linspace(0,2*np.pi,301)
R = 8
r = 1
d = 3

x = (R + r) * np.cos(theta) - d * np.cos((R+r)*theta/r)
y = (R + r) * np.sin(theta) - d * np.sin((R+r)*theta/r)

plt.plot(x,y)
plt.axis("equal")
plt.show()

在此处输入图片说明

If you can't use numpy, you can do it with functions and loops : 如果您不能使用numpy,则可以使用函数和循环来实现:

import math
import matplotlib.pyplot as plt

def X(theta,R,r,d) : 
    return (R + r) * math.cos(theta) - d * math.cos((R+r)*theta/r)

def Y(theta,R,r,d) : 
    return (R + r) * math.sin(theta) - d * math.sin((R+r)*theta/r)

nbSamples=100
theta=[]
for i in range (nbSamples) : 
    theta.append(i/(nbSamples-1)*2*math.pi)


x=[]
y=[]    

R=8
r=1
d=3
for th in theta:

    x.append(X(th,R,r,d))
    y.append(Y(th,R,r,d))

plt.plot(x,y)
plt.axis("equal")
plt.show()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM