bar plot with different color bars depending on height

Hello to all,
I have two matrices, lets say the below:
x = [1:10]
y= [13, 25, 34, 65, 78, 92, 54, 46, 39, 5]
I need a bar plot (x,y) where each bar has a different color depending on its height (y value). Colors should be from blue (low values) to red (high values). I also need to create the respective colorbar with an asceding step of 10
How can I create this bar plot?
Thanks in advance

 Accepted Answer

hello Giannis
see code below and ouput here :
clc
clearvars
x = [1:10];
y= [13, 25, 34, 65, 78, 92, 54, 46, 39, 5];
%% main code
map = colormap('jet');
[mmap,nmap] = size(map);
data_min = min(y);
data_max = max(y);
f= figure(1), hold on
for k = 1:length(y)
h=bar(x(k),y(k));
% now define col value based on data value (min data value maps to colormap map index 1
% and max data value maps to colormap map last index);
ind = fix(1+(mmap-1)*(y(k)-data_min)/(data_max-data_min));
set(h, 'FaceColor', map(ind,:)) ;
% Display the values as labels at the tips of the bars.
xtips1 = h.XEndPoints;
ytips1 = h.YEndPoints + 3;
labels1 = string(h.YData);
text(xtips1,ytips1,labels1,'HorizontalAlignment','center')
end
xlabel('X axis')
ylabel('Y axis')
hold off
CBAR_ticks = 10*(fix(min(y)/10):ceil(max(y)/10));
caxis([min(CBAR_ticks),max(CBAR_ticks)])
hcb=colorbar('Ticks',CBAR_ticks,'TickLabels',split(num2str(CBAR_ticks)));
hcb.Title.String = "Y range";
hcb.Title.FontSize = 13;

5 Comments

Hello!! thank you for your answer. I wanted exactly that!! However when I run your code to my matlab (2019a) there is an error. It says:
"Unrecognized method, property, or field 'XEndPoints' for class 'matlab.graphics.chart.primitive.Bar'.
Error in test (line 18)
xtips1 = h.XEndPoints; "
There is something wrong with the XEndPoints... do you know what is going on?
Thank you
Giannis
ok I commented these lines and now it runs ok!!
I didnt understand the formula of 'ind' !! where you based to use this function?is it a common methodology?
By thw way, I understand that you are trying to find the respective row of the color from the map matrix based on the y value...
hello
I don't have the error (I run R2020b)
the ind formula is to actually set the color according to the colormap scale and the bar height.
I want to plot a 10 bars in bar graph with different colors
y=[20 10 5 3 12 18 25 20 30 40];
bar(y)
Can you help me for acheiving this

Sign in to comment.

More Answers (0)

Categories

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!