首先需要导入所用到的第三方库
from matplotlib import pyplot as plt
import numpy as np
“”"
给定圆心和半径,画圆
r :半径
x,y:圆心的坐标
“”"
def pint(r,x,y):
plt.figure() # 创建一个空白窗体
plt.title('Circle')
plt.xlabel('x')
plt.ylabel('y')
# 点的横坐标为a
a = np.arange(x-r,x+r,0.000001)
# 点的纵坐标为b
b = np.sqrt(np.power(r,2)-np.power((a-x),2))+y
plt.plot(a,b,color='r',linestyle='-')
plt.plot(a,-b,color='r',linestyle='-')
plt.scatter(0,0,c='b',marker='o')
plt.grid(True)
plt.show()
pint(2,0,0)
a = np.arange(x-r,x+r,0.000001)
class Circle:
r = 0 # 半径
x,y = (0,0) # 圆心
# 构造函数,初始化赋值
def __init__(self,r1,m,n):
self.r = r1
self.x = m
self.y = n
# 方法,画圆
def pint(self):
plt.figure() # 创建一个空白窗体
plt.title('Circle')
plt.xlabel('x')
plt.ylabel('y')
# 点的横坐标为a
a = np.arange(-2*np.pi,2*np.pi,0.00001)
# 点的纵坐标为b
b = np.sqrt(np.power(self.r,2)-np.power((a-self.x),2))+self.y
plt.plot(a,b,color='r',linestyle='-')
plt.plot(a,-b,color='r',linestyle='-')
plt.scatter(self.x,self.y,c='b',marker='o')
plt.axis([-4,4,-4,4])
plt.grid(True)
plt.show()
r = 2
x,y = (0,0)
y = Circle(r,x,y) # 实例化一个对象
y.pint() # 调用该对象的方法进行画圆
此处用的是
a = np.arange(-2*np.pi,2*np.pi,0.00001)
b = np.sqrt(np.power(self.r,2)-np.power((a-self.x),2))+self.y
圆的基本方程为:(x-x0)^2 + (y-y0)^2 =r^2 ,(x0,y0)为圆的圆心
已知x求y,则转换成b变量的式子
a_x = np.arange(0,2*np.pi,0.01)
a = x+r*np.cos(a_x)
b = y+r*np.sin(a_x)
plt.plot(a,b,coloe='r',linestyle='-'
plt.plot(a,-b,color='r',linestyle='-'
x = x0+r*cosα
y = y0+r*sinα
有的时候,坐标轴的横纵坐标尺度不一致,导致圆变的有点椭,可以采用matplotlib中的xlim和ylim来改变坐标轴的刻度
plt.xlim(-4,4)
plt.ylim(-4,4)