Skip to main content
 首页 » 编程设计

python之如何使用 Matplotlib 用户定义的颜色图找到白色

2025年05月04日15Free-Thinker

我用这个构造函数创建了一堆 RegularPolygons -

        node.brushShape = RegularPolygon((node.posX, node.posY), 
                            6, 
                            node.radius * 0.8, 
                            linewidth = 3, 
                            edgecolor = (1,1,1), 
                            facecolor = 'none', 
                            zorder = brushz) 

如您所见,我希望这些补丁的边缘是白色的。我将它们全部放入一个名为 brushShapes 的列表中,然后创建一个 PatchCollection -

self.brushShapesPC = PatchCollection(self.brushShapes, match_original=True) 

这种方式在保持边缘白色的情况下效果很好。但是,现在我想使用用户定义的颜色图 -

colormap = {'red':  ((0.0, 0.0, 0.0), 
               (0.25,0.0, 0.0), 
               (0.5, 0.8, 1.0), 
               (0.75,1.0, 1.0), 
               (1.0, 0.4, 1.0)), 
 
        'green': ((0.0, 0.0, 0.0), 
               (0.25,0.0, 0.0), 
               (0.5, 0.9, 0.9), 
               (0.75,0.0, 0.0), 
               (1.0, 0.0, 0.0)), 
 
        'blue':  ((0.0, 0.0, 0.4), 
               (0.25,1.0, 1.0), 
               (0.5, 1.0, 0.8), 
               (0.75,0.0, 0.0), 
               (1.0, 0.0, 0.0))}  

所以现在我的 PatchCollection 实例化是 -

self.brushShapesPC = PatchCollection(self.brushShapes, cmap=mpl.colors.LinearSegmentedColormap('SOMcolormap', self.colormap)) 

但是现在边缘和脸的颜色一样了!所以我需要做的是 - 使用新的颜色图确定白色的值是多少......并更改

edgecolor = (1,1,1) 

到

edgecolor = (whatever_white_is) 

在这个构造函数中 -

node.brushShape = RegularPolygon((node.posX, node.posY), 
                        6, 
                        node.radius * 0.8, 
                        linewidth = 3, 
                        edgecolor = (1,1,1), 
                        facecolor = 'none', 
                        zorder = brushz) 

是吗?我一直在努力确定白色的值(value)是多少。当我调出一个颜色条时,它显示白色就在中心......所以我已经尝试了(0.5,0.5,0.5),(0,1,0)等。任何人都可以帮我弄清楚我应该做什么放?是否有通用的方法来了解任何给定颜色图的白色是什么?

请您参考如下方法:

我认为您的做法有点倒退。没有完全通用的方法来确定颜色图中的白色是什么(它可能存在不止一次或根本不存在)。

但是,您可以在使用 PolyCollection 时仅指定多边形的边缘应为白色,同时仍然使用面的颜色图。只需指定 edgecolors 而不是 edgecolor。这有点令人困惑,但想法是它是复数,因为您可以指定多个值。另外,看看 RegularPolygonCollection

举个简单的例子:

import matplotlib.pyplot as plt 
from matplotlib.patches import RegularPolygon 
from matplotlib.collections import PatchCollection 
import numpy as np 
 
xy = np.random.random((10,2)) 
z = np.random.random(10) 
 
patches = [RegularPolygon((x,y), 5, 0.1) for x, y in xy] 
collection = PatchCollection(patches, array=z, edgecolors='white', lw=2) 
 
fig, ax = plt.subplots() 
# So that the white edges show up... 
ax.patch.set(facecolor='black') 
ax.add_collection(collection) 
ax.autoscale() 
 
plt.show()