bar plot with different color bars depending on height
조회 수: 25 (최근 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
댓글 수: 0
채택된 답변
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
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 Center 및 File Exchange에서 Annotations에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!