如何在MATLAB中标记色彩映射?

时间:2015-07-16 20:08:57

标签: matlab legend colormap

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

  1. 添加一个图例,我可以填写每种颜色的含义

  2. 将X轴的一部分分隔到我可以键入的位置"青色"在青色部分下面的x区域上,"黄色"在黄色部分下面的x区域。

  3. 要么是好的,哪一个更容易适合我。

    enter image description here

                    CYAN                         YELLOW
    

2 个答案:

答案 0 :(得分:3)

你想要这样的东西吗?这是非常基本的哈哈。

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'})

输出:

enter image description here

答案 1 :(得分:1)

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

%% // 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

导致: enter image description here

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

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

相关问题