如何向使用 matlab 生成的混淆矩阵添加垂直线?

How can I add vertical lines to my confusion matrix generated with matlab?

我使用以下代码生成我的混淆矩阵,这是我在互联网上找到的:

    confmat = C;
    labels = {'0', '1', '2', '3', '11' };
    numlabels = size(confmat, 1); % number of labels
    confpercent = 100*confmat./repmat(sum(confmat, 1),numlabels,1);
    imagesc(confpercent);
    Mycolors=[0 0.7 0.4; 1 0.9 0.9 ]
    colormap(flipud(Mycolors));
    textStrings = num2str([confpercent(:)], '%.1f%%\n');
    textStrings = strtrim(cellstr(textStrings));
    [x,y] = meshgrid(1:numlabels);
    hStrings = text(x(:),y(:),textStrings(:), ...
        'HorizontalAlignment','center');
    midValue = mean(get(gca,'CLim'));
    textColors = repmat(confpercent(:) > midValue,1,3);
    set(hStrings,{'Color'},num2cell(textColors,2));
    set(gca,'XTick',1:numlabels,... 'XTickLabel',labels,... 'YTick',1:numlabels,... 'YTickLabel',labels,...  'TickLength',[0 0]);

我得到了下一个矩阵

虽然我想在我的矩阵中添加垂直线以分隔值,以便我可以获得与下一个相似的值:

我可以使用 pcolor(confusion_matrix) 得到那些垂直线,但是百分比被转移到每个网格的角落,我得到了下一张图片:

使用另一个 axes 对象

处理不同 axes 属性时的经典 MATLAB 技巧。 基本上我们要创建一个新的 axes 对象,将它放在珍贵的对象之上,然后使其透明(无背景色)以便我们可以看到后面的内容,但我们将保持网格线清晰可见就在我们想要的地方。

所以在您的示例代码之后,立即添加:

ax1 = gca  ; % get handle of initial axes
ax2 = axes ; % create new axe and retrieve handle

lim = [0 numlabels] ; % Prepare X and Y properties
tks = 0:numlabels ;

% superpose the new axe on top, at the same position
set(ax2,'Position', get(ax1,'Position') );

% make it transparent (no color)
set(ax2,'Color','none') ;

% set the X and Y properties
set(ax2, ...
    'XLim',lim,'XTick',tks,'XTickLabel','' ,...
    'YLim',lim,'YTick',tks,'YTickLabel','' ) ;

% now set your grid properties
set(ax2,'GridColor','k','GridAlpha',1)

这会让你(数据有点不同,因为我随机生成了混淆矩阵):

当然,现在您可以完全控制网格线,因此您还可以通过 axes 的网格属性优化它们的显示方式。一些有趣的属性是:

  • GridLineStyle — 网格线的线条样式
  • GridColor — 网格线的颜色
  • GridAlpha — 网格线透明度
  • LineWidth — 线宽

有关详细信息,请查看 Axes Properties

的文档

嗯! 我找到了获得垂直线和水平线的要求的东西,这是简单地使用绘图添加线并按住:

我在问题中提到的代码末尾使用了下一个代码:

hold on
plot ([2 2],get(gca, 'YLim'), 'Color', [0.15, 0.15, 0.15],'LineWidth',0.5)
plot ([1 1],get(gca, 'YLim'), 'Color', [0.15, 0.15, 0.15],'LineWidth',0.5)
plot ([3 3],get(gca, 'YLim'), 'Color', [0.15, 0.15, 0.15],'LineWidth',0.5)
plot ([4 4],get(gca, 'YLim'), 'Color', [0.15, 0.15, 0.15],'LineWidth',0.5)

plot (get(gca, 'XLim'), [1 1], 'Color', [0.15, 0.15, 0.15],'LineWidth',0.5)
plot (get(gca, 'XLim'), [2 2], 'Color', [0.15, 0.15, 0.15],'LineWidth',0.5)
plot (get(gca, 'XLim'), [3 3], 'Color', [0.15, 0.15, 0.15],'LineWidth',0.5)
plot (get(gca, 'XLim'), [4 4], 'Color', [0.15, 0.15, 0.15],'LineWidth',0.5)

我使用了 1、2、3 和 4,因为我有四个 class 并且在每个 class 预测结果的末尾我需要绘制直线。 希望有用