How do I change the colors of Stack Plot bars for different variables

2 次查看(过去 30 天)
I want to change the colors of the stack bar individually for 3 different variables. I am following the color map property but it is not working. Here is my code. I want the 3rd variable color should be voilet.
color1 = [0.3, 0.5, 0.7]; % RGB color for Y1
color2 = [0.8, 0.2, 0.2]; % RGB color for Y2
color3 = [0.5, 0.2, 0.9]; % Adjusted RGB color for Y3 (violet)
% Plotting
figure('Position', [100, 100, 800, 600]);
% Define the x-coordinates for each group of bars
x_pos = 1:numel(x_values);
Stack_Parameters = {'AC','JRCP\_Base','Base/Subbase/Subgrade'};
y1_MD = [data(:,1),data(:,3),data(:,5)];
y_sum_MD=sum(y1_MD,2);
y_MD=(y1_MD./y_sum_MD)*100;
y1=y_MD(:,1);
y2=y_MD(:,2);
y3=y_MD(:,3);
bar(x_pos,[y1,y2,y3],'stacked');
% Set custom colors for each bar
colormap([color1; color2; color3]);
% Show all values in the bars
%text(x_pos, y(:,1), compose('%.1f%%', data(:, 1)), 'HorizontalAlignment', 'center', 'VerticalAlignment', 'bottom');
%text(x_pos, percent_group1 + percent_group2, compose('%.1f%%', data(:, 2)), 'HorizontalAlignment', 'center', 'VerticalAlignment', 'bottom');
ylabel('Percentage, %');
% Set y-axis limit to 100%
ylim([0 100]);
xticks(x_pos);
title('FWD 3 Layered Analysis (Modulus)');
xlabel('Station');
legend(Stack_Parameters,'Location', 'best','orientation','horizontal');

采纳的回答

Voss
Voss 2024-3-26
编辑:Voss 2024-3-26
One way is to set the FaceColor directly:
% random data:
x_values = 1:10;
data = rand(10,5);
color1 = [0.3, 0.5, 0.7]; % RGB color for Y1
color2 = [0.8, 0.2, 0.2]; % RGB color for Y2
color3 = [0.5, 0.2, 0.9]; % Adjusted RGB color for Y3 (violet)
% Plotting
figure('Position', [100, 100, 800, 600]);
% Define the x-coordinates for each group of bars
x_pos = 1:numel(x_values);
Stack_Parameters = {'AC','JRCP\_Base','Base/Subbase/Subgrade'};
y1_MD = data(:,[1,3,5]);
y_sum_MD=sum(y1_MD,2);
y_MD=(y1_MD./y_sum_MD)*100;
hb = bar(x_pos,y_MD,'stacked');
% Set custom colors for each bar
set(hb,{'FaceColor'},{color1; color2; color3})
% Show all values in the bars
%text(x_pos, y(:,1), compose('%.1f%%', data(:, 1)), 'HorizontalAlignment', 'center', 'VerticalAlignment', 'bottom');
%text(x_pos, percent_group1 + percent_group2, compose('%.1f%%', data(:, 2)), 'HorizontalAlignment', 'center', 'VerticalAlignment', 'bottom');
ylabel('Percentage, %');
% Set y-axis limit to 100%
ylim([0 100]);
xticks(x_pos);
title('FWD 3 Layered Analysis (Modulus)');
xlabel('Station');
legend(Stack_Parameters,'Location', 'best','orientation','horizontal');
  3 个评论

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Migrate GUIDE Apps 的更多信息

产品


版本

R2024a

Community Treasure Hunt

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

Start Hunting!

Translated by