Overlaying a Bar chart with 2 Y-axes and 2 legends. My code below plots data x and y versus xx. I want the right Y-axes to have the amplitudes of data "y". And also I will like a legend for data "x" on the top right corner. Any suggestions?

4 views (last 30 days)
y= [1.5 5.5 2.46 1.36; 6.5 44.35 3.46 16; 9.5 99 50 2.33;17.76 39.38 12.7 2.0;...
20 35 16.18 2.35];
x=[17 19 3 3;70 66 22 25;65 225 42 16; 75 292 32 16; 132 205 29 18];
xx=[1 2 3 4 5];
w1 = .7;
h(:,1)=bar(xx,y,w1,'FaceColor','flat');
legend(h(:,1), {'Imaging','Mechanical','Cyclotron','Software'},'Location','northeast');
grid on
hold on
w2=0.4;
h(:,2)=bar(xx,x,w2,'FaceColor','flat');
set(gca,'XTickLabel',{'Sep-Dec, 2014','2015','2016','2017','2018'});
legend(h(:,2), {'Imaging','Mechanical','Cyclotron','Software'},'Location','northwest');
hold off
chart try.png

Answers (1)

Vedant Shah
Vedant Shah on 21 Feb 2025
After generating both plots, we can add the legends with proper titles. Additionally, we need to hide the visibility of the extra axes to ensure that both legends are visible. The dual axes will be displayed using the yyaxis function. For further information, please refer to the following documentation:
web(fullfile(docroot, "/matlab/ref/axes.html"))
web(fullfile(docroot, "/matlab/ref/legend.html"))
web(fullfile(docroot, "/matlab/ref/yyaxis.html"))
Below is the code that accomplishes the desired functionality:
% Data for bar charts
y = [1.5 5.5 2.46 1.36; 6.5 44.35 3.46 16; 9.5 99 50 2.33; 17.76 39.38 12.7 2.0; 20 35 16.18 2.35];
x = [17 19 3 3; 70 66 22 25; 65 225 42 16; 75 292 32 16; 132 205 29 18];
xx = [1 2 3 4 5];
w1 = 0.7;
w2 = 0.4;
% Create figure
figure;
% Create bar chart for y data
yyaxis left
h1 = bar(xx, y, w1, 'FaceColor', 'flat');
ylabel('Y Data')
% Set different colors for y data bars
colors_y = [0.8 0.2 0.2; 0.2 0.8 0.2; 0.2 0.2 0.8; 0.8 0.8 0.2];
for k = 1:size(y, 2)
h1(k).CData = colors_y(k, :);
end
% Overlay bar chart for x data on the right Y-axis
yyaxis right
h2 = bar(xx, x, w2, 'FaceColor', 'flat');
ylabel('X Data')
% Set different colors for x data bars
colors_x = [0.5 0.5 0.5; 0.3 0.3 0.3; 0.7 0.7 0.7; 0.4 0.4 0.4];
for k = 1:size(x, 2)
h2(k).CData = colors_x(k, :);
end
l1 = legend(h1, {'Imaging', 'Mechanical', 'Cyclotron', 'Software'});
title(l1, 'Y Data');
ah1=axes('position',get(gca,'position'),'visible','off');
l2 = legend(ah1,h2, {'Imaging_2', 'Mechanical', 'Cyclotron', 'Software'},'Location','NorthWest');
title(l2, 'X Data');
% Set x-axis labels
set(gca, 'XTickLabel', {'Sep-Dec, 2014', '2015', '2016', '2017', '2018'});
% Enable grid
grid on
In this code, I have also applied distinct colors to each of the bars to enhance differentiation and visualization.
The output generated by this code is as follows:

Products


Release

R2018b

Community Treasure Hunt

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

Start Hunting!