如何在 MATLAB 中标记颜色图?

How To Label Colormaps in MATLAB?

我有以下来自 imagesc 的图像(一些矩阵的条目对应于这些颜色)。青色和黄色都意味着不同的东西。我想:

  1. 添加图例,我可以在其中填写每种颜色的含义

  2. 将 X 轴的部分分隔到我可以在青色部分下方的 x 区域中键入 "cyan",在黄色部分下方的 x 区域中键入 "yellow" .

两者都可以,哪个更容易,哪个更适合我。

                CYAN                         YELLOW

你想要这样的东西吗?很基础哈哈

clc
clear
close all

%// Dummy array
A = repmat([0 0 0 1 1 1],6,1);

imagesc(A)

hold on

%// Dummy data to add legend
scatter(0,0,1,'b','filled')
scatter(0,0,1,'r','filled')

axis off
colorbar

%// Get axis coordinates (x first and then y)
ax = axis;

%// Add text. You can easily adjust the x-offset depending on how many colors you have.
text(ax(2)/4+ax(1),ax(4)+.2,'Blue','Color','b','FontSize',20,'HorizontalAlignment','Center')
text(3*ax(2)/4+.2,ax(4)+.2,'Red','Color','r','FontSize',20,'HorizontalAlignment','Center')

%// Add legend
legend({'Blue';'Red'})

输出:

这是另一个选项,恰好 友好:

%% // Initialization
clear variables; close all force; clc;
%% // Generate some data
fakeData = magic(3)-0.5;
fakeData_horz = fakeData(:)'; %//'
fakeNames = cellstr(strcat('color',num2str((1:9)'))); %//'
fakeNameMapping = fakeNames(randperm(numel(fakeData)));
%% // Create figure
hFig = figure('Position',[680,488,758,610],'Resize','off');

%% // Top left example
cLims = [0 numel(fakeData)+1];
hSp = subplot(2,2,1); 
imagesc(fakeData); axis image; set(hSp,'XTick',[],'YTick',[]);
colorbar; caxis(cLims); 
[XX,YY] = meshgrid(1:size(fakeData,1),1:size(fakeData,2));
text(XX(:),YY(:),fakeNameMapping,'HorizontalAlignment','center');

%% // Bottom example
hSp = subplot(2,2,3:4);
cLims = [0 numel(fakeData)+1]; %Not required here since unchanged
imagesc(fakeData_horz); axis image; set(hSp,'XTick',[],'YTick',[]);
colorbar; caxis(cLims); 
drawnow; %// This command will allow the annotations to be positioned properly
for ind1=1:numel(fakeData_horz)
    newPos = [hSp.Position(1)+hSp.Position(3)/numel(fakeData_horz) * (ind1-1),...
              hSp.Position(2)*1.6,... %1.6 is chosen for the demo
              hSp.Position(3)/numel(fakeData_horz),...
              0.05]; % 0.05 is chosen for the demo; play around with it
    h= annotation('textbox',newPos,'String',fakeNameMapping{ind1},...
        'LineStyle','none','HorizontalAlignment','center');
end

%% // Top right example
hSp = subplot(2,2,2);
cLims = [0 numel(fakeData)]; %// cLims is a bit different here!
imagesc(fakeData); axis image; set(hSp,'XTick',[],'YTick',[]);
caxis(hSp,cLims); colormap(hSp,parula(numel(fakeData)));
cb = colorbar; %// This time we need a handle to the colorbar
cb.Ticks = (hSp.CLim(1):hSp.CLim(2))+0.5; %// Set the tick positions
cb.TickLabels = fakeNames; %// Set the tick strings

结果是:

注意:除非使用更智能的文本定位计算,否则绘制后图形的大小不应更改(在第二个示例中),因为这样文本就不再保留在应有的位置。


编辑:添加了另一个选项,其中仅标记了颜色栏。