修改 Matplotlib PatchCollection 中的特定补丁

Sch*_*ddi 2 python matplotlib

假设我使用第三方函数,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]
Run Code Online (Sandbox Code Playgroud)

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

我假设我需要访问存储在该对象中的补丁列表PatchCollection但是,在对类似问题“matplotlib Change a Patch in PatchCollection”的回答中,建议使用其子类来PatchCollection跟踪在公共列表属性中添加到其中的补丁,但考虑到该集合是在第三方功能,此解决方案不适用于我的情况。

Imp*_*est 5

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

在问题的具体示例中,只需设置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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述