如何在Python中为Shapely多边形添加径向颜色渐变?
实现Shapely圆的径向颜色渐变(中心深、边缘透明)
解决方案思路
Matplotlib的fill_between无法直接实现径向透明度渐变,需要通过生成渐变图像+圆形遮罩的方式,为每个Shapely圆添加中心实色、边缘透明的径向渐变效果。
修改后的完整代码
import matplotlib.pyplot as plt from shapely.geometry import Point from colorir import PolarGrad import numpy as np from matplotlib.patches import PathPatch from matplotlib.path import Path def create_radial_gradient_circle(center_x, center_y, radius, base_color): # 生成网格计算到圆心的距离 y, x = np.mgrid[-radius:radius:100j, -radius:radius:100j] dist = np.sqrt(x**2 + y**2) # 创建径向透明度渐变:中心透明度1,边缘透明度0,超出半径的区域完全透明 alpha = np.where(dist <= radius, 1 - dist/radius, 0) # 将基础颜色转换为RGBA格式 from matplotlib.colors import to_rgba base_rgba = to_rgba(base_color) # 构造RGBA渐变图像 img = np.zeros((100, 100, 4)) img[..., 0] = base_rgba[0] img[..., 1] = base_rgba[1] img[..., 2] = base_rgba[2] img[..., 3] = alpha # 创建圆形遮罩,确保只显示圆内的渐变 circle_path = Path.unit_circle() circle_patch = PathPatch(circle_path, facecolor='none') # 将渐变图像添加到坐标轴,并应用遮罩 ax = plt.gca() ax.add_patch(circle_patch) ax.imshow(img, extent=[center_x - radius, center_x + radius, center_y - radius, center_y + radius], clip_path=circle_patch, clip_on=True) # 初始化基础参数 x = 0 y = 0 h = 1.73205080757 # 生成原始点集 color_points = [ Point(x, y), Point((x + 2), y), Point((x - 2), y), Point((x + 1), (y + h)), Point((x - 1), (y + h)), Point((x + 1), (y - h)), Point((x - 1), (y - h)) ] # 圆的半径(对应原代码中的buffer值) radius = 2 # 生成每个圆的基础颜色渐变 p_grad = PolarGrad(["#2b70f3", "#f3ae2b"]) p_grad_colors = p_grad.n_colors(7) # 创建画布与坐标轴 fig = plt.figure() ax = fig.add_subplot() fig.subplots_adjust(top=0.85) ax.set_aspect('equal') # 逐个绘制带径向渐变的圆 for point, color in zip(color_points, p_grad_colors): create_radial_gradient_circle(point.x, point.y, radius, color) # 设置坐标轴范围,确保所有圆完整显示 ax.set_xlim(-4, 4) ax.set_ylim(-4, 4) plt.show()
关键代码说明
- 渐变图像生成:用
numpy.mgrid生成网格,计算每个像素到圆心的距离,以此生成从1到0的透明度渐变通道,结合基础颜色得到RGBA渐变图像。 - 圆形遮罩:通过
PathPatch创建圆形路径,将渐变图像裁剪为圆形,避免显示圆外的渐变区域。 - 替换原绘制逻辑:不再使用
fill_between填充单一颜色,而是用imshow加载渐变图像并应用遮罩,实现每个圆的径向渐变效果。
内容的提问来源于stack exchange,提问作者Doda
相关产品推荐
相关产品推荐

