Matlab绘图之高亮部分直方图

时间:2024-03-12 16:13:53

前一阵子想绘制一个直方图,这在Matlab中其实很简单,bar函数就可以做到。但是如果想要如下图那样,只是高亮一部分,或者改变这一部分的属性,好像目前bar函数还没有办法做到这样。

解决这个问题可以采用这样的思路:建立两个单独直方图。每个图形用一个直方图表示。这样就可以修改你想修改的地方。

第一步:生成一个叫做ydata的数组

rng(0)
ydata = rand(1,15);

第二步:创建一个相同大小的逻辑数组(假设要将位置9设置为红色)

sel = false(size(ydata));
sel(9) = true;

第三步:用该逻辑数组将ydata复制两份:一份在逻辑数组为真是设置为nan;另一份与之相反。将这两组画在一张图上。

y1 = ydata;
y1(sel) = nan;

y2 = ydata;
y2(~sel) = nan;

figure
h1 = bar(y1);
hold on
h2 = bar(y2);

 现在画出来的应该是这样的:

现在就可以将想要区分的部分设置成想要的颜色,如:

h2.FaceColor = \'red\';

 

 还可以改变宽度,等等其他属性,

ax = gca;
h1.FaceColor = ax.ColorOrder(1,:);
h2.FaceColor = ax.ColorOrder(3,:);
h1.BarWidth = .5;
h2.BarWidth = 1;
h2.EdgeColor = \'none\';

 

以下是全部过程:

function highlightable_bar(ydata)
  % An example of how to use two bar charts to highlight
  % selected values.
  %
  % Create 2 bar charts.
  h1 = bar(ydata);
  hold on;
  h2 = bar(nan(size(ydata)));
  hold off;
  % You can set whatever properties you like on each of them to make
  % them look as different as you would like.
  h2.FaceColor = \'red\';
  % Add a button down listener to each bar chart
  h1.ButtonDownFcn = @btndwn;
  h2.ButtonDownFcn = @btndwn;
  function btndwn(~,evd)
    % Figure out which bar the user clicked on. The eventdata tells us
    % where the mouse was when the click occurred.
    x = round(evd.IntersectionPoint(1));
    % Create 2 YData arrays from the original one. The first
    % has a nan for the selected bar. The second has nans for
    % all of the other bars.
    sel = false(size(ydata));
    sel(x) = true;
    h1.YData = ydata;
    h1.YData(sel) = nan;
    h2.YData = ydata;
    h2.YData(~sel) = nan;
  end
end

 原文参看:http://blogs.mathworks.com/graphics/2014/11/11/highlighting-parts-of-charts/