简体   繁体   中英

Matlab: 1D array to RGB triplets with colormap

I'm trying to draw a set of rectangles, each with a fill color representing some value between 0 and 1. Ideally, I would like to use any standard colormap.

Note that the rectangles are not placed in a nice grid, so using imagesc , surf , or similar seems unpractical. Also, the scatter function does not seem to allow me to assign a custom marker shape. Hence, I'm stuck to plotting a bunch of Rectangles in a for-loop and assigning a FillColor by hand.

What's the most efficient way to compute RGB triplets from the scalar values? I've been unable to find a function along the lines of [r,g,b] = val2rgb(value,colormap). Right now, I've built a function which computes 'jet' values, after inspecting rgbplot (jet). This seems a bit silly. I could, of course, obtain values from an arbitrary colormap by interpolation, but this would be slow for large datasets.

So, what would an efficient [r,g,b] = val2rgb(value,colormap) look like?

You have another way to handle it: Draw your rectangles using patch or fill specifying the color scale value, C , as the third parameter. Then you can add and adjust the colorbar:

x = [1,3,3,1,1];
y = [1,1,2,2,1];
figure
for ii = 1:10
    patch(x + 4 * rand(1), y + 2 * rand(1), rand(1), 'EdgeColor', 'none')
end
colorbar

With this output:

在此处输入图片说明

I think erfan's patch solution is much more elegant and flexible than my rectangle approach.

Anyway, for those who seek to convert scalars to RGB triplets, I'll add my final thoughts on the issue. My approach to the problem was wrong: colors should be drawn from the closest match in the colormap without interpolation. The solution becomes trivial; I've added some code for those who stumble upon this issue in the future.

% generate some data
x = randn(1,1000);

% pick a range of values that should map to full color scale
c_range = [-1 1];

% pick a colormap
colormap('jet');

% get colormap data
cmap = colormap;

% get the number of rows in the colormap
cmap_size = size(cmap,1);

% translate x values to colormap indices
x_index = ceil( (x - c_range(1)) .* cmap_size ./ (c_range(2) - c_range(1)) );

% limit indices to array bounds
x_index = max(x_index,1);
x_index = min(x_index,cmap_size);

% read rgb values from colormap
x_rgb = cmap(x_index,:);

% plot rgb breakdown of x values; this should fall onto rgbplot(colormap)
hold on;
plot(x,x_rgb(:,1),'ro');
plot(x,x_rgb(:,2),'go');
plot(x,x_rgb(:,3),'bo');
axis([c_range 0 1]);
xlabel('Value');
ylabel('RGB component');

With the following result: 使用“jet”颜色图从标量值计算的 RGB 分量

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM