bar plot with different color bars depending on height

34 views (last 30 days)
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

Mathieu NOE
Mathieu NOE on 1 Jun 2021
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
Vartika Agarwal
Vartika Agarwal on 19 Nov 2021
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)

Tags

Community Treasure Hunt

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

Start Hunting!