Barchart colorbar colors from second vector

3 次查看(过去 30 天)
I have a variant of this question:
I have a bar chart where I am colouring the bars based on a second corresponding vector.
%%
clear
close all
clc
ids1 = [2,4,5,6,8];
meanVals = [0.2,0.204,0.199,0.208,0.19];
velMns = [16.384,16.98,17.182,18.001,18.40];
figure;
b=bar(ids1,meanVals);
xticks(ids1)
grid on
labels = pad(string(b(1).YData),6);
labelsShrt=[extractBetween(labels,1,5)]';
xtips = b(1).XEndPoints;
ytips = b(1).YEndPoints;
text(xtips,ytips,labelsShrt,'HorizontalAlignment','center',...
'VerticalAlignment','bottom','FontSize',8);
title('mean values')
ylim([min(meanVals)-0.02 max(meanVals)+0.005])
% set bar color
MaxV = 20;
MinV = 5;
range=MaxV-MinV;
colors = jet(range); % Define a colormap
b.FaceColor = 'flat';
for II = 1:length(ids1)
barColorID = round(velMns(II),0)-MinV;
b.CData(II,:) = colors(barColorID,:);
end
cbar = colorbar;
caxis([MinV MaxV]);
This works as desired apart from the colormap of the colorbar, which does not correspond to the second vector.
Thanks in advance

采纳的回答

Voss
Voss 2024-5-19
You need to set the colormap of the figure or axes.
%%
clear
close all
clc
ids1 = [2,4,5,6,8];
meanVals = [0.2,0.204,0.199,0.208,0.19];
velMns = [16.384,16.98,17.182,18.001,18.40];
figure;
b=bar(ids1,meanVals);
xticks(ids1)
grid on
labels = pad(string(b(1).YData),6);
labelsShrt=[extractBetween(labels,1,5)]';
xtips = b(1).XEndPoints;
ytips = b(1).YEndPoints;
text(xtips,ytips,labelsShrt,'HorizontalAlignment','center',...
'VerticalAlignment','bottom','FontSize',8);
title('mean values')
ylim([min(meanVals)-0.02 max(meanVals)+0.005])
% set bar color
MaxV = 20;
MinV = 5;
range=MaxV-MinV;
colors = jet(range); % Define a colormap
b.FaceColor = 'flat';
for II = 1:length(ids1)
barColorID = round(velMns(II),0)-MinV;
b.CData(II,:) = colors(barColorID,:);
end
cbar = colorbar;
caxis([MinV MaxV]);
set(gca,'Colormap',colors)

更多回答(0 个)

类别

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

标签

产品


版本

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by