如何在 Matplotlib 中绘制圆
要在 Matplotlib
中绘制圆,我们可以使用以下任何一种方法:
-
matplotlib.patches.Circle()
方法 - 圆方程
- 点的散点图
在 Matplotlib 中使用 matplotlib.patches.Circle()
方法绘制圆
语法:
matplotlib.patches.Circle((x, y), r=5, **kwargs)
其中,(x, y)
是圆心,r
是半径,默认值为 5
。
我们需要使用 add_artist
方法在轴上添加 Circle
,因为 Circle
是 Artist
的子类。
import matplotlib.pyplot as plt
figure, axes = plt.subplots()
draw_circle = plt.Circle((0.5, 0.5), 0.3)
axes.set_aspect(1)
axes.add_artist(draw_circle)
plt.title('Circle')
plt.show()
要绘制没有填充颜色的圆,我们应该将 fill
参数设置为 False
。
import matplotlib.pyplot as plt
figure, axes = plt.subplots()
draw_circle = plt.Circle((0.5, 0.5), 0.3,fill=False)
axes.set_aspect(1)
axes.add_artist(draw_circle)
plt.title('Circle')
plt.show()
通过使用 gcf()
和 gca()
函数将圆快速插入到现有图中,我们可以使上述代码更简单。
import matplotlib.pyplot as plt
figure, axes = plt.subplots()
draw_circle = plt.Circle((0.5, 0.5), 0.3,fill=False)
plt.gcf().gca().add_artist(draw_circle)
plt.title('Circle')
axes.set_aspect(1)
plt.show()
在 Matplotlib 中用圆方程绘制圆
圆的参数方程
圆的参数方程为 x=r*cos(theta)
和 y=r*sin(theta)
。
import numpy as np
import matplotlib.pyplot as plt
theta = np.linspace(0, 2*np.pi, 100)
radius = 0.3
a = radius*np.cos(theta)
b = radius*np.sin(theta)
figure, axes = plt.subplots(1)
axes.plot(a, b)
axes.set_aspect(1)
plt.title('Circle using Parametric Equation')
plt.show()
圆方程的中心半径形式
我们还可以使用圆方程的中心半径形式绘制圆。
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-0.5, 0.5, 100)
y = np.linspace(-0.5, 0.5, 100)
a, b = np.meshgrid(x, y)
C = a**2+b**2-0.2
figure, axes = plt.subplots()
axes.contour(a,b,C,[0])
axes.set_aspect(1)
plt.show()
点的散点图
我们还可以使用 scatter()
方法在 Matplotlib 中绘制一个圆,并使用 s
参数调整半径。圆的面积是 pi/4*s
。
import matplotlib.pyplot as plt
plt.scatter(0, 0, s=4000)
plt.title('Circle')
plt.xlim(-0.75,0.75)
plt.ylim(-0.75,0.75)
plt.show()
相关文章
Pandas DataFrame DataFrame.shift() 函数
发布时间:2024/04/24 浏览次数:133 分类:Python
-
DataFrame.shift() 函数是将 DataFrame 的索引按指定的周期数进行移位。
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
Pandas read_csv()函数
发布时间:2024/04/24 浏览次数:254 分类:Python
-
Pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 DataFrame 中。
Pandas 多列合并
发布时间:2024/04/24 浏览次数:628 分类:Python
-
本教程介绍了如何在 Pandas 中使用 DataFrame.merge()方法合并两个 DataFrames。
Pandas loc vs iloc
发布时间:2024/04/24 浏览次数:837 分类:Python
-
本教程介绍了如何使用 Python 中的 loc 和 iloc 从 Pandas DataFrame 中过滤数据。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串