如何在Matplotlib中绘制环形(仅保留两圆间的环形区域)
实现Matplotlib环形区域(大圆内、小圆外)的显示方法
要保留大圆内部、小圆外部的环形区域,核心思路是通过路径组合生成环形路径,替代原来的两个叠加圆。具体操作如下:
修改后的完整代码
import numpy as np import matplotlib.pyplot as plt from math import sqrt from matplotlib.path import Path from matplotlib.patches import PathPatch # 绘制网格点 for x in np.arange(0.5, 10, 1): for y in np.arange(0.5, 10, 1): plt.scatter(x, y, color='blue', s=10) d = 3 r_small = sqrt(2) * (d + 0.5) r_large = sqrt(2) * (d + 1 + 0.5) # 创建大圆和小圆的基础图形 circle_large = plt.Circle((0, 0), r_large) circle_small = plt.Circle((0, 0), r_small) # 获取路径及坐标变换(将单位圆路径转换为实际大小和位置) path_large = circle_large.get_path() trans_large = circle_large.get_transform() path_small = circle_small.get_path() trans_small = circle_small.get_transform() # 将小圆路径应用坐标变换,匹配实际位置和半径 path_small = trans_small.transform_path(path_small) # 组合路径:用大圆路径减去小圆路径,得到环形路径 ring_path = Path.make_compound_path(path_large, path_small) # 创建环形填充块并添加到画布 ring_patch = PathPatch(ring_path, color='blue', alpha=0.5) plt.gca().add_patch(ring_patch) print(f"小圆半径: {r_small}") print(f"大圆半径: {r_large}") # 坐标轴及网格设置 plt.yticks(np.arange(0, 10.01, 1)) plt.xticks(np.arange(0, 10.01, 1)) plt.xlim(0,10) plt.ylim(0,10) plt.gca().invert_yaxis() plt.gca().set_aspect('equal', adjustable='box') plt.grid() plt.show()
关键步骤说明
- 路径获取与变换:
Circle对象的路径默认是单位圆,需要通过get_transform()获取坐标变换规则,将其转换为对应半径和位置的实际路径。 - 环形路径生成:使用
Path.make_compound_path()将大圆路径和小圆路径组合,Matplotlib会自动将后续路径从前面的路径中扣除,从而得到环形区域。 - 绘制环形:将生成的环形路径通过
PathPatch转换为可绘制的图形块,设置颜色和透明度后添加到画布即可。
内容的提问来源于stack exchange,提问作者Simd
相关产品推荐
相关产品推荐

