【问题标题】:Can you use a colorbar to display what number of a for loop you're on?您可以使用颜色条来显示您正在进行的 for 循环数吗?
【发布时间】:2019-11-26 20:14:15
【问题描述】:

我正在绘制矩阵的特征值,因为我使用从 0 到 10 的线性间隔向量更改该矩阵内的值。我想要做的是使用颜色条来跟踪 for 循环的数量我上线了。也就是说,我希望当 i = 1 时颜色条为红色,并且绘制的点为红色,当 i = 长度(K)时,我希望颜色条为绿色,并绘制点是绿色的。有没有办法做到这一点?我已经查看了 colorbar 的帮助文档,但我无法理解它。

【问题讨论】:

标签: matlab plot colorbar


【解决方案1】:

不,colorbar 并不是一个进度条。你可以通过例如实现你想要的。使用area。请参阅代码中的 cmets 进行解释。

% generate some example data, probably you'd do this in the loop.
N = 100;
eig_vals = rand(1,N) + 2*sin((1:N)*pi/20);

% make colormap from red to green. 
red = [1, 0, 0];
green = [0, 1, 0];
cmap = interp1([1, N], [red; green], 1:N);
cmap_nan = NaN(N, 3); % some colormap with NaNs as placeholder. 

% Initialize the figure. I chose to use two subplots, one for the data, 
% one for the progressbar. The data subplot spans 4 horizontal subplot 
% 'positions', and the progressbar is plotted in the 5th subplot.

figure(1); clf; 
ax(1) = subplot(1,5,1:4);
% initialize a scatter object.
s = scatter(1:N, zeros(N, 1), [], cmap_nan, 'filled');
% and set the axis limits to the range you expect
ax(1).XLim = [0 N];
ax(1).YLim = [min(eig_vals), max(eig_vals)];

% second subplot for the progressbar. Initially, I make N area plots, and 
% set the FaceColors to white. 
ax(2) = subplot(1,5,5);
a = area([1 2]+N, ones(2,N)/N, 'FaceColor', 'w', 'LineStyle', 'none');
% remove ticks and set YLim.
ax(2).XTick = [];
ax(2).YTick = [];
ax(2).YLim = [0 1];

% loop over data, or calculate data in the loop. 
for k = 1:N
    % code to calculate stuff? 
    % ... 
    % add the new data point in the scatterplot
    s.YData(k) = eig_vals(k);
    % set the color of the datapoint
    s.CData(k, :) = cmap(k, :);
    % and set the color of the appropriate face in the progressbar
    a(k).FaceColor = cmap(k,:);
    % update the figure:
    drawnow
end

% That's it.

【讨论】:

    【解决方案2】:

    您是在寻找动画还是静态人物?如果是静态图,这里有一个简单的解决方案:

    % set colormap: green to red
    N = 11;
    K = cat(2, ...
        linspace(1, 0, N).', ... % red value: starting from 1, going down to 0
        linspace(0, 1, N).', ... % green value: starting from 0, going up to 1
        zeros(N, 1)); % blue value: no blue
    colormap(K);
    
    % make plot
    clf; % clear figure
    colorbar; % plot colorbar
    hold on;
    for i = 1 : N
        [x, y] = deal(rand(1), rand(1)); % random point in unit square
        plot(x, y, 'o', ...
            'MarkerEdgeColor', K(i, :), 'MarkerFaceColor', K(i, :)); % set color of point
    end
    hold off;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-06
      • 1970-01-01
      相关资源
      最近更新 更多