在Matlab中绘制一个颜色代表值的矩形

sup*_*ggs 2 matlab

我想绘制一些矩形,所有矩形都有一个相关的值.我可以使用值绘制点,scatter(x,y,[],value);rectangle函数似乎没有这样的功能.

谢谢

alr*_*kai 5

您可以设置矩形颜色,但不能直接模拟您的工作方式scatter.使用时rectangle,您有两种颜色选择; 边缘颜色和面部颜色.要设置边缘颜色,请使用表示RGB值的3元素向量,以使每个元素都在[0,1]范围内.例如

%make some arbitrary rectangle (in this case, located at (0,0) with [width, height] of [10, 20])
rect_H = rectangle('Position', [0, 0, 10, 20]); 
%sets the edge to be green
set(rect_H, 'EdgeColor', [0, 1, 0])             
Run Code Online (Sandbox Code Playgroud)

矩形的面部颜色是其填充颜色 - 您可以通过使用颜色字符串(例如,"g"为绿色,"r"为红色等)或以相同方式使用3元素矢量来设置作为边缘颜色属性.

例如,这两个命令将具有相同的效果:

set(rect_H, 'FaceColor', 'r'); 
set(rect_H, 'FaceColor', [1, 0, 0]); 
Run Code Online (Sandbox Code Playgroud)

在您的情况下,您只需要将一个值(无论形式如何)映射到3元素RGB颜色矢量.我不确定你的着色目标是什么,但是如果所有你想要它的所有矩形颜色都不同,你可以使用一些映射函数:

color_map = @(value) ([mod((rand*value), 1), mod((rand*value), 1), mod((rand*value), 1)])
Run Code Online (Sandbox Code Playgroud)

然后有

set(rect_H, 'FaceColor', color_map(value));
Run Code Online (Sandbox Code Playgroud)

value假定在哪里是标量.此外,如果你想在一条线上做所有事情,scatter你也可以这样做:

rectangle('Position', [x, y, w, h], 'FaceColor', color_map(value));
Run Code Online (Sandbox Code Playgroud)

更新:为了colorbar使其工作得很好,您必须保存每个3元素颜色向量,并将其传递给matlab内置函数colormap.然后打电话colorbar.我不知道你正在使用什么样的颜色映射,所以只是为了说明:

figure;
hold on;

%have 20 rectangles
num_rects = 20;

%place your rectangles in random locations, within a [10 x 10] area, with
%each rectange being of size [1 x 1]
random_rectangles = [rand(num_rects, 2)*10, ones(num_rects,2)];

%assign a random color mapping to each of the 20 rectangles
rect_colors = rand(num_rects,3);

%plot each rectangle
for i=1:num_rects
    rectangle('Position', random_rectangles(i,:), 'FaceColor', rect_colors(i,:));
end

%set the colormap for your rectangle colors
colormap(rect_colors);
%adds the colorbar to your plot
colorbar
Run Code Online (Sandbox Code Playgroud)

希望这就是你所问的......