Matlab:为单个组着色,而不是组中的单个条

时间:2018-11-08 21:11:04

标签: matlab

这是我的代码:

Positions=[1:5];
Gap_Duration=[4,4,4,4,4,4;
2,2,2,2,2,2;
3,3,3,3,3,3;
4,4,4,4,4,4; 
0,0,0,0,0,24];
H = barh(Positions,Gap_Duration,'stacked')
set(H([1 3 5]),'Visible','off')
ax = gca;
ax.YTick = [Positions];
ax.YTickLabel = {'AllOut','Port1In','Port2In','DeliverReward','Total Time Duration'};
xlabel('Time')
title('Lever Press Frequency')

我想使水平y轴上的条形各为1种颜色(因此,所有“传递奖励”条形均为红色,所有“ Port2In”条形均为蓝色,等等)。

1 个答案:

答案 0 :(得分:1)

要解决此问题,请为每行生成单独的水平条形图,同时将其余元素的宽度保持为NaN,这样就不会绘制任何多余的图形。即

Lp = length(Positions);  
colors = hsv(Lp);    %Generating group colors (or define custom colors if needed)
hold on;
for k=1:Lp 
    GapD = NaN(size(Gap_Duration));   %Initializing a dummy Gap_Duration matrix
    GapD(k,:) = Gap_Duration(k,:);    %Filling with the content of the current row
    H = barh(Positions, GapD, 'stacked');
    set(H, 'FaceColor', colors(k,:)); %Making the color same for all current bars
    set(H([1 3 5]),'Visible','off');  %This condition is from your code     
end

output