gpt4 book ai didi

python - 在 seaborn 情节上设置剪辑

转载 作者:太空宇宙 更新时间:2023-11-03 10:55:43 25 4
gpt4 key购买 nike

我在剪裁 seaborn 图(特别是 kdeplot)时遇到问题,因为我认为根据 this example in the matplotlib docs 会相当简单.

例如下面的代码:

import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns

fig = plt.figure()
ax = fig.add_subplot(111, frameon=False, xticks=[], yticks=[])

random_points = np.array([p for p in np.random.random(size=(100, 2)) if 0 < p[0] < 1 and 0 < p[1] < 1])

kde = sns.kdeplot(random_points[:,0], random_points[:,1], ax=ax)

xmin, xmax = kde.get_xlim()
ymin, ymax = kde.get_ylim()

patch = mpl.patches.Circle(((xmin + xmax)/2, (ymin + ymax) / 2), radius=0.4)
ax.add_patch(patch)
kde.set_clip_path(patch)

结果如下:

enter image description here

我想裁剪这个结果,这样 KDE 等高线就不会出现在圆圈之外。到目前为止,我还没有找到一种方法...这可能吗?

最佳答案

Serenity 的答案适用于简单的形状,但当形状包含超过三个左右的顶点时会因未知原因而崩溃(我什至难以确定确切的参数)。对于足够大的形状,填充会流入边缘应在的位置,as for example here .

然而,它确实让我沿着正确的道路思考。虽然似乎不可能仅仅使用 matplotlib natives(也许他提供的代码中有错误?),但使用 shapely 时很容易图书馆,这是为这样的任务而设计的。

生成形状

在这种情况下,您将需要 shapely 的 symmetric_difference方法。 symmetric difference是这个切出操作的集合论名称。

在这个例子中,我加载了一个曼哈顿形状的多边形作为 shapely.geometry.Polygon 对象。我不会在这里隐藏初始化过程,它很容易做到,而且一切都是你所期望的。

我们可以使用 manhattan.envelope 在我们的 manhattan 周围画一个框,然后应用差异。这是以下内容:

unmanhattan = manhattan.envelope.symmetric_difference(manhattan)

做什么让我们:

enter image description here

将其添加到图中

好的,但这是一个 shapely 对象而不是 matplotlib Patch,我们如何将它添加到图中? descartes 库处理这种转换。

unmanhattan_patch = descartes.PolygonPatch(unmanhattan)

这就是我们所需要的!现在我们做:

unmanhattan_patch = descartes.PolygonPatch(unmanhattan)
ax.add_patch(unmanhattan_patch)
sns.kdeplot(x=points['x_coord'], y=points['y_coord'], ax=ax)

并得到:

enter image description here

再做一些工作将其扩展到 View 中的其余多边形(纽约市),我们可以获得以下最终结果:

enter image description here

关于python - 在 seaborn 情节上设置剪辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41310821/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com