首页 > 解决方案 > Matplotlib 补丁 - 去除颜色覆盖

问题描述

我目前正在开展一个项目,根据卫星数据绘制 MH370 的路线,基本上它涉及绘制指示在给定时间可能区域的补丁。每个图我有 3 组数据 - 一组具有 100% 的置信区间,一组为 95%,然后也是 50% 的置信区间。然而,对于每个时间戳,都有多个可能的点,它们最终都相互重叠,看起来很可怕。有没有办法禁用此叠加层并使其使圆圈全部形成一个连续区域?

我已经检查并在这里看到了类似的东西:Matplotlib:当曲线重叠时如何防止透明颜色覆盖?但它不适用于补丁,我想不出如何让它在这种情况下工作。不幸的是,由此产生的几何形状非常不规则,无法用任何形状来描述。

例子:

fig = plt.figure(figsize=(8, 8))
ax = fig.add_subplot(1, 1, 1)
ax.set_xlim([0,7])
ax.set_ylim([0,7])

ax.add_patch(mpatches.Circle(xy=[2.8, 2.8], radius= 1, color = 'red', alpha = 0.1))
ax.add_patch(mpatches.Circle(xy=[2.8, 2.8], radius= 1.5, color = 'green', alpha = 0.1))
plt.plot(2.8, 2.8, 'rx', markersize=9, markeredgewidth = 5)

ax.add_patch(mpatches.Circle(xy=[3.3, 3.5], radius= 1, color = 'red', alpha = 0.1))
ax.add_patch(mpatches.Circle(xy=[3.3, 3.5], radius= 1.5, color = 'green', alpha = 0.1))
plt.plot(3.3, 3.5, 'rx', markersize=9, markeredgewidth = 5)

ax.add_patch(mpatches.Circle(xy=[4.25, 4], radius= 1, color = 'red', alpha = 0.1))
ax.add_patch(mpatches.Circle(xy=[4.25, 4], radius= 1.5, color = 'green', alpha = 0.1))
plt.plot(4.25, 4, 'rx', markersize=9, markeredgewidth = 5)

plt.show()

显示 3 个重叠圆圈的图表,突出显示问题中讨论的重叠问题

标签: pythonmatplotlib

解决方案


感谢推荐这个包的 JohanC,即“Shapely”。我使用了在他们网站上找到的教程,即本节:https ://shapely.readthedocs.io/en/latest/manual.html#shapely.ops.unary_union

这是代码和输出:

from matplotlib import pyplot
from shapely.geometry import Point
from shapely.ops import unary_union
from descartes import PolygonPatch

poly1 = Point(2.8, 2.8).buffer(1)
poly2 = Point(3.3, 3.5).buffer(1)
poly3 = Point(4.25, 4).buffer(1)

poly4 = Point(2.8, 2.8).buffer(1.5)
poly5 = Point(3.3, 3.5).buffer(1.5)
poly6 = Point(4.25, 4).buffer(1.5)

polygons = [poly1, poly2, poly3]
polygons_outer = [poly4, poly5, poly6]

fig = pyplot.figure(1, figsize=(12, 5), dpi=90)
ax1 = fig.add_subplot(121)

u = unary_union(polygons)
u2 = unary_union(polygons_outer)
patch2b = PolygonPatch(u, fc='red', ec='red', alpha=0.2, zorder=2)
ax1.add_patch(patch2b)

patch2c = PolygonPatch(u2, fc='green', ec='green', alpha=0.1, zorder=1)
ax1.add_patch(patch2c)

ax1.set_xlim(0, 7)
ax1.set_ylim(0, 7)

pyplot.show()

已解决原帖中的问题


推荐阅读