如何根据单独的值向量更改线条的颜色作为绘图的一部分?
How to change the color of lines as part of a plot based on a separate vector of values?
我有一组值存储在 350x130 矩阵中,r,我用它在 Matlab 中创建一个简单的绘图:
figure;
plot(r)
有没有办法使用另一个 350x1 向量 v 为 r 的结果线着色? V 包含整数的集合,在本例中,整数从 1 到 4 不等。
我想象调用看起来像这样,其中,r 是 350x130,v 是 350x1:
figure;
plot(r,v)
让我们定义一些示例数据:
r = rand(10,15);
v = randi(4,1,15);
方法一(更好玩):使用逗号分隔列表
这将创建一个元胞数组并将其转换为 comma-separated list to call plot
as plot(x1, y1, s1, x2, y2, s2, ...)
. The colors are limited to be defined as plot
's linespec strings(例如 'g'
或 'c+'
)。
linespecs = {'r' 'g' 'b' 'm'};
c = repmat({1:size(r,1)}, 1, size(r,2));
c(2,:) = num2cell(r, 1);
c(3,:) = linespecs(v);
plot(c{:})
方法二(更具可读性和灵活性):使用循环
linespecs = {'r' 'g' 'b' 'm'};
hold on
for k = 1:size(r,2)
plot(r(:,k), linespecs{v(k)})
end
此方法允许使用 colormap 指定 任意颜色 ,不限于 linespec 字符串:
colors = winter(4); % arbitrary colormap
hold on
for k = 1:size(r,2)
plot(r(:,k), 'color', colors(v(k),:))
end
我有一组值存储在 350x130 矩阵中,r,我用它在 Matlab 中创建一个简单的绘图:
figure;
plot(r)
有没有办法使用另一个 350x1 向量 v 为 r 的结果线着色? V 包含整数的集合,在本例中,整数从 1 到 4 不等。
我想象调用看起来像这样,其中,r 是 350x130,v 是 350x1:
figure;
plot(r,v)
让我们定义一些示例数据:
r = rand(10,15);
v = randi(4,1,15);
方法一(更好玩):使用逗号分隔列表
这将创建一个元胞数组并将其转换为 comma-separated list to call plot
as plot(x1, y1, s1, x2, y2, s2, ...)
. The colors are limited to be defined as plot
's linespec strings(例如 'g'
或 'c+'
)。
linespecs = {'r' 'g' 'b' 'm'};
c = repmat({1:size(r,1)}, 1, size(r,2));
c(2,:) = num2cell(r, 1);
c(3,:) = linespecs(v);
plot(c{:})
方法二(更具可读性和灵活性):使用循环
linespecs = {'r' 'g' 'b' 'm'};
hold on
for k = 1:size(r,2)
plot(r(:,k), linespecs{v(k)})
end
此方法允许使用 colormap 指定 任意颜色 ,不限于 linespec 字符串:
colors = winter(4); % arbitrary colormap
hold on
for k = 1:size(r,2)
plot(r(:,k), 'color', colors(v(k),:))
end