【Python 练习实例63】画椭圆。
【分析】复杂图形或公式可以用Python的第三方库Matplotlib来实现。
椭圆的公式为:
【实例】Demo1:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import matplotlib.pyplot as plt import numpy as np #设置画布 fig = plt.figure(figsize=(6,6)) ax = fig.add_subplot(111) # 设置椭圆方程 a, b = 4, 2 theta = np.arange(0, 2*np.pi, np.pi/100) x = a * np.cos(theta) y = b * np.sin(theta) ax.plot(x,y) # 修改x, y轴的缩放比例 ax.set_ylim([-5, 5]) ax.set_xlim([-5, 5]) # 显示椭圆公式 ax.text(-3.2, -0.2, r'$ \frac{x^2}{a^2} + \frac{y^2}{b^2} =1 (a>b>0) $', fontsize=22) plt.show() |
输出:
Demo2:通过matplotlib中的饼图来画一个“伪”椭圆
1 2 3 4 5 6 7 8 9 10 11 12 |
import matplotlib.pyplot as plt # 设置饼图的数据,两个数据分布为1.然后展示是将所有数据填充同一个颜色即可。 slice = [1,1] plt.pie(slice, colors=['b', 'b'], explode=(0,0)) # 显示椭圆公式 fig = plt.figure() ax = fig.add_subplot(111) ax.text(-0.75, -0.05, r'$ \frac{x^2}{a^2} + \frac{y^2}{b^2} =1 (a>b>0) $', fontsize=22) plt.show() |
输出: