gpt4 book ai didi

python - 修改 Matplotlib PatchCollection 中的特定补丁

转载 作者:行者123 更新时间:2023-12-01 01:15:33 24 4
gpt4 key购买 nike

假设我使用第三方函数 magic_plot(data, ax),它根据提供的数据向轴添加补丁集合。让我们进一步假设我想更改已添加的特定补丁的颜色。我怎么做?

from numpy.random import rand

from matplotlib.collections import PatchCollection
from matplotlib.patches import Circle
import matplotlib.pyplot as plt

def magic_plot(data, ax):
"""
A third-party plotting function, not modifiable by end-users.
"""
lst = []
for i in range(10):
patch = Circle((rand(), rand()), rand())
lst.append(patch)
collection = PatchCollection(lst)
ax.add_collection(collection)

ax = plt.gca()
data = rand(100)

# create the plot:
magic_plot(data, ax)

# obtain the PatchCollection created by magic_plot():
collection = ax.collections[0]

如上所示,我可以从 ax.collections 的轴中检索集合,但如何从这里继续?

我假设我需要访问存储在此 PatchCollection 对象中的补丁列表。然而,在回答类似问题"matplotlib change a Patch in PatchCollection" ,建议使用 PatchCollection 的子类来跟踪在公共(public)列表属性中添加到其中的补丁,但考虑到该集合是在第三方函数中创建的,此解决方案是对我来说不是一个选择。

最佳答案

更新补丁的形状几乎是不可能的,如链接的问题所示。然而,在这里您想要更改补丁的颜色。这应该容易得多。

在问题的具体示例中,只需设置集合的facecolor即可实现。

import numpy as np
np.random.seed(50)

from matplotlib.collections import PatchCollection
from matplotlib.patches import Circle
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors

def magic_plot(data, ax):
"""
A third-party plotting function, not modifiable by end-users.
"""
lst = []
for i in range(10):
patch = Circle((np.random.rand(), np.random.rand()), np.random.rand()/9)
lst.append(patch)
collection = PatchCollection(lst)
ax.add_collection(collection)

ax = plt.gca()
data = np.random.rand(100)

# create the plot:
magic_plot(data, ax)
ax.autoscale()

# obtain the PatchCollection created by magic_plot():
collection = ax.collections[0]

n = len(collection.get_paths())
facecolors = collection.get_facecolors()
if len(facecolors) == 1 and n != 1:
facecolors = np.array([facecolors[0]] * n)

# change the facecolor of the fourth patch (index=3)
facecolors[3] = mcolors.to_rgba("crimson")
collection.set_facecolor(facecolors)

plt.show()

enter image description here

关于python - 修改 Matplotlib PatchCollection 中的特定补丁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54388115/

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