I would like to plot a number of rectangles, all of which have an associated value. I can plot points with values using scatter(x,y,[],value); but the rectangle function does not seem to have such functionality.
Thank you
You can set the rectangle color, although not quite as a direct analog to how you do with scatter. When using rectangle, you have two color options; the edge color and the face color. To set the edge color, use a 3-element vector representing the RGB values, such that each element is within the range [0, 1].
e.g.
%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])
The face color of the rectangle is its fill-color -- you can set that by using a color string (e.g. 'g' is green, 'r' is red, etc) or by using a 3-element vector in the same manner as the edge color property.
e.g. these 2 commands will have the same effect:
set(rect_H, 'FaceColor', 'r');
set(rect_H, 'FaceColor', [1, 0, 0]);
In your case, you would just need some mapping for your value (whatever form it may be in) to a 3-element RGB color vector. I'm not sure what your goal is for the coloring, but if all you're looking for it to have all the rectangle colors be different, you could use some mapping function along the lines of:
color_map = @(value) ([mod((rand*value), 1), mod((rand*value), 1), mod((rand*value), 1)])
then have
set(rect_H, 'FaceColor', color_map(value));
where value is assumed to be a scalar. Also, if you're looking to do everything on one line akin to scatter you can do that too:
rectangle('Position', [x, y, w, h], 'FaceColor', color_map(value));
UPDATE:
To have this work nicely with colorbar, you'd have to save each of your 3-element color vectors, and pass it to the matlab built-in function colormap. Then call colorbar. I have no idea what kind of color mapping you're using, so just for the sake of illustration:
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
Hopefully that's what you were asking about...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With