Matplotlib的PatchCollections与set_array:如何匹配面色和边色?

4 投票
1 回答
1160 浏览
提问于 2025-04-18 06:59

我写了一段Python代码,用来生成不同尺寸的矩形。不过,我遇到一个问题,就是矩形的边框颜色和填充颜色不一致。以下是我代码中相关的部分:

# Mapping row information to geometry and color of plot points
x = np.array(info[0])-time
y = np.array(info[1])
x_width = np.array(info[2])
y_width = np.array(info[3])
colors =  np.array(info[4])
colors = np.log10(colors)

patches = []

# Save rectangle object-datapoints to patches
(time_min,time_max) = (x-x_width/2., x+x_width/2.)
(freq_min, freq_max) = (y-y_width/2., y+y_width/2.)

for i in range(len(x)):
    f_min_plot = max(freq_min[i],f_min)
    patches.append(Rectangle((time_min[i], f_min_plot), x_width[i], freq_max[i]-f_min_plot)) 

fig = pl.figure()
pl.rc('text', usetex=True) 
ax = fig.add_subplot(111)
p = PatchCollection(patches, match_original=False)
p.set_array(colors)
ax.add_collection(p)
cbar = pl.colorbar(p)
#cbar.set_label('$\log_{10}$ SNR', rotation = 270)
pl.xlabel("Time-%.1f" %(time)) 
pl.ylabel("Frequency")
pl.semilogy()
pl.title("%s1 omicron triggers"%(detector))
pl.xlim(-time_interval,time_interval)
pl.ylim(20,2000)
pl.savefig("%s/%s1-omicron-trigs-%.1f-%d.png" %(file_path, detector, time,  time_interval))

这段代码生成的矩形默认是黑色边框的填充颜色。我希望边框颜色能和填充颜色一致。我尝试过把边框去掉,设置edgecolor = "none",但这样一来,有些矩形(特别是那些宽度很小的)颜色就看不太清楚了。我还尝试在Rectangle()语句中加上color = matplotlib.cm.jet(color_norm[i] # color_norm是“归一化”的颜色数组:color/max(color)),并在PatchCollections()语句中设置match_original = True,但也没有效果。看起来set_array()这个函数最终决定了颜色的显示。我找不到关于set_array具体作用和用法的详细文档。

有没有办法让我的代码绘制的矩形边框颜色和填充颜色完全一致呢?非常感谢大家对这个问题的帮助。

1 个回答

2

你可以使用 set_edgecolor 命令,并通过 'face' 这个关键词来设置边缘颜色,像这样:

p.set_edgecolor('face')

这样做对我来说很有效,它把边缘颜色设置成和面颜色一样。

撰写回答