bar plot with different color bars depending on height
15 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Giannis Nikolopoulos
le 1 Juin 2021
Commenté : Vartika Agarwal
le 19 Nov 2021
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 commentaires
Réponse acceptée
Mathieu NOE
le 1 Juin 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 commentaires
Vartika Agarwal
le 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
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Annotations dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!