how to assign a color to individual bars in a bar chart using a colormap based on a separate series of values?
17 次查看(过去 30 天)
显示 更早的评论
I have the following 10 x 3 matrix:
1 3.43 0.80
2 3.24 0.10
3 3.20 0.60
4 3.15 0.90
5 3.07 0.70
6 2.82 1.00
7 2.76 0.50
8 2.62 0.70
9 2.61 0.60
10 2.55 0.90
I want to plot this as a bar chart using the first 2 columns, but assign colors to each bar based on its value in the 3rd column, using some form of a colormap, such that the color of each bar reflects the value in the 3rd column.
I can get this far easily:
>> x=matrix(:,1);
>> y=matrix(:,2);
>> bar(x,y)
to get this figure, no problem:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/226485/image.jpeg)
But how do I now change the color of each bar based on its corresponding value in the 3rd column of the matrix, using a colormap?
0 个评论
采纳的回答
Monika Phadnis
2019-6-27
You can change color of a particular bar using FaceColor property of bar graph. I followed this documentation example under Data - CData property.
%create map of third column values to colors you want
%colors are stored as RGB value matrix
colormap = containers.Map({'0.1','0.5','0.6','0.7','0.8','0.9','1.0'},{[0 0.4470 0.7410],[0.8500 0.3250 0.0980],[0.9290 0.6940 0.1250],[0.4940 0.1840 0.5560],[0.4660 0.6740 0.1880],[0.3010 0.7450 0.9330],[0.6350 0.0780 0.1840]});
b = bar(x,y,'FaceColor','flat');
%this example changes color of first row value in matrix
%get the value of the third column of matrix of first row to map
%get the corresponding RGB value vector of color stored in map
b.CData(1,:) = colormap(string(mat(1,3)))
You can follow similar approach for all row values.
Hope this helps.
更多回答(1 个)
Monika Phadnis
2019-6-28
Check the dimensions of the matrices you are concatenating. Since the vals2colormap returns a 100x3 matrix (considering you wanted to map 100 entries), the dimension of y values should 100xsome_value.
Take a transpose or reshape the matrices and try again.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Line Plots 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!