如何在MATLAB中更改条形颜色 [英] How to change bars colour in MATLAB
问题描述
我是编程新手,所以我正在学习MATLAB入门知识,我想知道如何在MATLAB中更改条形的颜色.
I am new to programming so I am learning introductory to MATLAB I was wondering how you could change colours of bar in MATLAB.
这是我的脚本.有人可以帮忙吗!
this is my script. Can someone please help!!
x =[1:8]
for y = [20 30 40 50 60 70 80]
bar(x,y)
if y < 40
col = 'b';
else if y > 40
col= 'g';
end
end
end
我也尝试过bar(x,y,r),但是它不起作用
i also tried bar(x,y, r) but it doesnt work
推荐答案
虽然这对于您的特定问题来说是过大的,但是通常来说,要根据条的高度更改条的颜色,您可以在条上应用colormap
.这主要来自 bar
文档.
Whilst this is overkill for your specific question, in general, to change the colour of bars depending on their height, you can apply a colormap
to the bars. This is mainly from the bar
documentation.
x = 1:8;
y = 10*x;
h=bar(y); %// create a sample bar graph
对于颜色图MAP
,请执行以下操作:
For the colormap MAP
, you do this:
colormap(MAP)
ch = get(h,'Children');
fvd = get(ch,'Faces');
fvcd = get(ch,'FaceVertexCData');
[zs, izs] = sort(y);
for i = 1:length(x)
row = izs(i);
fvcd(fvd(row,:)) = i;
end
set(ch,'FaceVertexCData',fvcd)
hold off
例如,使用内置的colormap
hsv
And, for example, using the builtin colormap
hsv
, you get
但是在这种情况下,我们需要一个非常具体的色彩图,
But in this case we want a very specific colormap,
b=40 %// the cut-off for changing the colour
MAP=zeros(length(x),3); %// intialise colormap matrix
MAP(y<b,:)=repmat([0 0 1],sum(y<b),1); %// [0 0 1] is blue, when y<40
MAP(y>=b,:)=repmat([0 1 0],sum(y>=b),1); %// [0 1 0] is green, for y>=40
colormap(MAP)
给出
这篇关于如何在MATLAB中更改条形颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!