如何根据间隔绘制具有多种颜色的干图

How to plot a stem graph with multiple colors depending on the interval

假设您有一个在区间 [0:3*period] 上定义的 Matlab 函数,有没有办法生成一个柱状图,以便每个周期都有不同颜色的柱状图?

这里有一些代码,您可以明白我的意思:

T = 36;
n = [ 0 : 3 * T ];
x1 = cos( 5 * pi * n / 6 );
x2 = cos( 4 * pi * n / 9 );
z = x1 + x2;

现在我想用三个周期的干图绘制 z(n),但每个周期必须是不同的颜色([0:T] 为蓝色,[T:2T] 为红色,[ 2T : 3T ] 为绿色)。有没有办法根据图的区间指定柱状图的颜色?

这可以通过根据参考期 (logical indexing) and, subsequently, by plotting a separate stem for every group on the same axis (hold approach) 将数据分成三个独立的组来轻松实现:

% Build data...
T = 36;
n = 1:(3*T);
z = cos(5 * pi() * n / 6) + cos(4 * pi() * n / 9);

% Define the splitting indices...
idx1 = n <= T;
idx2 = (n > T) & (n <= 2*T);
idx3 = (n > 2*T) & (n <= 3*T);

% Plot the data groups into the current axis...
stem(n(idx1),z(idx1),'fill','-b');
hold on;
stem(n(idx2),z(idx2),'fill','-r');
stem(n(idx3),z(idx3),'fill','-g');
hold off;

这是最终结果: