【发布时间】:2014-10-14 23:24:37
【问题描述】:
我正在 Matlab 中绘制条形图。我想知道是否可以根据一个简单的条件来确定条形的颜色?我希望所有积极的酒吧都说蓝色,消极的酒吧都是红色的。如果可能的话,您能告诉我如何在 MATLAB 中执行此操作吗?
【问题讨论】:
-
你能把你的条形图声明也放在帖子里吗?
标签: matlab
我正在 Matlab 中绘制条形图。我想知道是否可以根据一个简单的条件来确定条形的颜色?我希望所有积极的酒吧都说蓝色,消极的酒吧都是红色的。如果可能的话,您能告诉我如何在 MATLAB 中执行此操作吗?
【问题讨论】:
标签: matlab
是的,有可能,请参阅 MATLAB Central 上的 this solution。
这是从中提取的一些示例代码。数据的第三列用于确定将哪种颜色应用于每个条形。在您的情况下,您只需要检查每个值是正数还是负数并相应地更改颜色。
data = [.142 3 1;.156 5 1;.191 2 0;.251 4 0];
%First column is the sorted value
%Second column is the index for the YTickLabel
%Third column is the reaction direction
% Data(1,3) = 1 -> bar in red
% Data(1,3) = 0 -> bar in blue
% For each bar, check direction and change bar colour
H = data(:, 1);
N = numel(H);
for i=1:N
h = bar(i, H(i));
if i == 1, hold on, end
if data(i, 3) == 1
col = 'r';
else
col = 'b';
end
set(h, 'FaceColor', col)
end
【讨论】:
或者,您可以包括您的条件(此处为 data>0 和 data<0),如下所示:
data = rand(8,1) - .5;
figure(1);
clf;
hold on;
bar(data.*(data>0), 'b');
bar(data.*(data<0), 'r');
【讨论】:
x=randperm(5*length(data),length(data)); 是我用来说服自己你的 sn-p 确实做了它应该做的事情的向量。