bar plot with different color bars depending on height

15 次查看(过去 30 天)
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

采纳的回答

Mathieu NOE
Mathieu NOE 2021-6-1
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 个评论
Vartika Agarwal
Vartika Agarwal 2021-11-19
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

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Annotations 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by