如何在3D图中使用色彩图?

时间:2017-09-08 09:38:19

标签: matlab colors matlab-figure colorbar colormap

此问题链接到my previous post

考虑以下代码:

%% How to plot each matrix in a cell in 3d plot(1 matrix with 1 color) ?
% Generate Sample data cell A(1x10 cell array)
clear; clc;
A = cell(1,10); % cell A(1x10 cell array)
for kk = 1:numel(A)
  z = 10*rand()+(0:pi/50:10*rand()*pi)';
  x = 10*rand()*sin(z);
  y = 10*rand()*cos(z);
  A{kk} = [x,y,z];
end

% Plot point of each matrix in one figure with different color
figure
hold on;
for i = 1:numel(A)%run i from 1 to length A

  C = repmat([i],size(A{i},1),1);%create color matrix C  
  scatter3(A{i}(:,1),A{i}(:,2),A{i}(:,3),C,'filled');
end
grid on;
view(3); % view in 3d plane
colorbar;

这是上述代码的图像结果:

output

我的问题:
如果我想使用"彩色地图"要显示与矩阵数对应的颜色,怎么办呢?
示例:在发布的代码中,我在单元格内有10个矩阵(A{1}A{2}A{3},...,A{10}A,那么如何使色条显示图中使用的10种颜色,以及如何显示1到10的10个数字,对应于图中使用的10种颜色(如图所示)?

1 个答案:

答案 0 :(得分:1)

在以下代码行中

C = repmat([i],size(A{i},1),1);%create color matrix C  
scatter3(A{i}(:,1),A{i}(:,2),A{i}(:,3),C,'filled');

scatter3的第四个输入参数,您将其命名为C,但未指定颜色。它用于指定绘制圆的大小。仅仅因为你将其命名为C,MATLAB就不会自动识别你的颜色。您获得了不同的颜色,因为您正在使用hold on绘制多个点。

来自my previous answer

的实际问题和构建
newA = vertcat(A{:});                   %Concatenating all matrices inside A vertically

numcolors = numel(A);                   %Number of matrices equals number of colors
colourRGB = jet(numcolors);             %Generating colours to be used using jet colormap
colourtimes = cellfun(@(x) size(x,1),A);%Determining num of times each colour will be used
colourind = zeros(size(newA,1),1);      %Zero matrix with length equals num of points
colourind([1 cumsum(colourtimes(1:end-1))+1]) = 1;
colourind = cumsum(colourind);          %Linear indices of colours for newA

scatter3(newA(:,1), newA(:,2), newA(:,3), [] , colourRGB(colourind,:),'filled');
%However if you want to specify the size of the circles as well as in your
%original question which you mistakenly wrote for color, use the following line instead:
% scatter3(newA(:,1), newA(:,2), newA(:,3), colourind , colourRGB(colourind,:),'filled');
grid on;
view(3);                                %view in 3d plane 
colormap(colourRGB);                    %using the custom colormap of the colors we used
%Adjusting the position of the colorbar ticks
caxis([1 numcolors]);
colorbar('YTick',[1+0.5*(numcolors-1)/numcolors:(numcolors-1)/numcolors:numcolors],...
    'YTickLabel', num2str([1:numcolors]'), 'YLim', [1 numcolors]);

得出以下结果:

out1

如果您想在代码中错误地更改圆圈的大小,请使用代码中提到的相关绘图线。使用它会产生以下结果:

out2