如何在分组条形图的顶部绘制一条线?

时间:2017-05-01 12:45:13

标签: matlab plot bar-chart

我有一个分组的条形图,我想比较这些值。我知道我想用线条来形象化它。我尝试了以下代码,输出也是如下

Y=rand(5,5)
str = {'A'; 'B'; 'C'; 'D'; 'E';};
bar_widh=0.2;
h = bar(Y,bar_widh);
hold on;plot(Y,'b');
set(gca, 'XTickLabel',str, 'XTick',1:numel(str))
grid on
l = cell(1,5);
l{1}='P'; l{2}='Q'; l{3}='R'; l{4}='S'; l{5}='T'; 
legend(h,l);

我得到了以下输出:

enter image description here

我想要显示最小数量/更大数量的柱子。在某些情况下,较大的值是坏的。你能帮我画一下与条相同的颜色吗

我输出如下

enter image description here

1 个答案:

答案 0 :(得分:2)

你可以试试这个:

Y=rand(5,5);
str = {'A'; 'B'; 'C'; 'D'; 'E';};
bar_widh=0.2;

figure; hold on;grid on
h = bar(Y,bar_widh);

% to highlight the minimum of each group, 
% copy data into a new matrix
Y_ = Y; 
% find the minimum values and make the rest zeors
Y_(Y_~=repmat(min(Y_,[],1),size(Y,1),1)) = 0;
% then plot with so sort of highlighting
h2 = bar(Y_,0.5);

pause(0.1) % pause to allow bars to be drawn

% now go through each group of bars and plot the line
for i = 1:numel(h)
    x = h(i).XData + h(i).XOffset; % find the x coordinates where the bars are plotted
    ax = plot(x,Y(:,i)); % plot the line
    % set color of the bars the same as the line
    h(i).FaceColor = ax.Color; 
    h2(i).FaceColor = ax.Color;
end

set(gca, 'XTickLabel',str, 'XTick',1:numel(str))
legend('P','Q','R','S','T');
  

h(i).XData

是第i组条的中心坐标。

例如,在您的情况下:

h(1).XData = [ 1 2 3 4 5 ]; % group P
h(2).XData = [ 1 2 3 4 5 ]; % group Q
...
h(5).XData = [ 1 2 3 4 5 ]; % group T
  

h(i).XOffset

是组中每个条与其对应中心坐标的偏移值。

例如,在您的情况下:

h(1).XOffset = -0.3077; % group P
h(2).XOffset = -0.1538; % group Q
...
h(5).XOffset = 0.3077; % group T

不突出显示最小值 enter image description here

突出显示最小值 enter image description here

相关问题