Skip to main content
 首页 » 编程设计

python之在 matplotlib 和 seaborn 中修改颜色条

2025年05月04日31xiaohuochai

我正在尝试保存使用 seaborn 生成的图像。图像是 4x4 混淆矩阵('confmat' np.array)。我了解到,当我以矢量格式保存图像时,某些观众会遇到导致颜色条上出现白线的问题,引用自 matplotlib 引用:

It is known that some vector graphics viewer (svg and pdf) renders white gaps between segments of the colorbar. This is due to bugs in the viewers not matplotlib. As a workaround the colorbar can be rendered with overlapping segments:

cbar = colorbar()

cbar.solids.set_edgecolor("face")

draw()

但是,我无法按照建议进行操作。

这是我做的:

import seaborn as sns 
import matplotlib.pyplot as plt 
 
cmap=plt.cm.Blues 
 
fig, ax = plt.subplots() 
     
ax = sns.heatmap(confmat, annot=True, cmap=cmap) 
ax.set_title('title') 
ax.tick_params( 
    axis='both',          # changes apply to the x-axis 
    which='both',      # both major and minor ticks are affected 
    bottom='off',      # ticks along the bottom edge are off 
    top='off',         # ticks along the top edge are off 
    labelbottom='off',  # labels along the bottom edge are off 
    labelleft='off', 
    right='off') 
 
fig.savefig('confusion_matrix.svg', format='svg') 

我尝试使用 colorbar

cbar = ax.colorbar() 

但是得到一个错误AttributeError: 'AxesSubplot' object has no attribute 'colorbar'.

我搜索了解决方案并在此处发现了一些建议使用 plt.imshow() 获取颜色条对象的问题,但我对我现在正在做的事情完全感到困惑。 有人可以建议并在可能的情况下解释为什么实现 matplotlib 文档为 colorbar 提供的解决方案吗?

请您参考如下方法:

import numpy as np 
import seaborn as sns 
import matplotlib.pyplot as plt 
 
x = np.random.randn(10, 10) 
 
f, ax = plt.subplots() 
sns.heatmap(x) 
cbar_ax = f.axes[-1] 
cbar_solids = cbar_ax.collections[0] 
cbar_solids.set_edgecolor("face") 
f.savefig("heatmap.svg")