I want to apply a different color to the bar in yyaxis.

12 views (last 30 days)
I want to apply a different color to the bar in yyaxis.
Without yyaxis, the color applies well on the bar graph,
If I try to use yyaxis function, the colors are unified blue.
For example,
figure(2), grid on, hold on
X = [1, 2, 3] ;
Y_1 = [ 1, 2, 3 ; 6, 4, 2 ; 1, 7, 4 ];
Y_2 = [ 10, 12, 21];
yyaxis left
bar(X , Y_1(: ,1 : 3)');
yyaxis right
plot(X , Y_2(:, 1 : 3 ),'-o');
legend('Y_1_1', 'Y_1_2', 'Y_1_3', 'Y_2_1')
Thank you for help!

Accepted Answer

Garmit Pant
Garmit Pant on 30 Jun 2022
To add colours to the bars, you just need to use the colororder() function as demonstrated below:
figure(2), grid on, hold on
X = [1, 2, 3] ;
Y_1 = [ 1, 2, 3 ; 6, 4, 2 ; 1, 7, 4 ];
Y_2 = [ 10, 12, 21];
yyaxis left
bar(X , Y_1(: ,1 : 3)');
colororder('default')
yyaxis right
plot(X , Y_2(:, 1 : 3 ),'-o');
legend('Y_1_1', 'Y_1_2', 'Y_1_3', 'Y_2_1')

More Answers (3)

KSSV
KSSV on 30 Jun 2022
figure(2), grid on, hold on
X = [1, 2, 3] ;
Y_1 = [ 1, 2, 3 ; 6, 4, 2 ; 1, 7, 4 ];
Y_2 = [ 10, 12, 21];
yyaxis left
h = bar(X , Y_1(: ,1 : 3)');
yyaxis right
plot(X , Y_2(:, 1 : 3 ),'-o');
legend('Y_1_1', 'Y_1_2', 'Y_1_3', 'Y_2_1')
color = {'r','g','b'} ;
for i = 1:3
set(h(i),'FaceColor',color{i})
end

Abhishek Tiwari
Abhishek Tiwari on 30 Jun 2022
Hi,
It is possible to do so by specifying different colour for each bar. This can be accomplished by changing 'FaceColor' for each plotted bar. There are multiple ways to do so, one of which is:
X = [1, 2, 3] ;
Y_1 = [ 1, 2, 3 ; 6, 4, 2 ; 1, 7, 4 ];
Y_2 = [ 10, 12, 21];
yyaxis left
b = bar(X , Y_1(: ,1 : 3)');
b(1).FaceColor = 'blue';
b(2).FaceColor = 'green';
b(3).FaceColor = 'yellow';
yyaxis right
plot(X , Y_2(:, 1 : 3 ),'-o');
legend('Y_1_1', 'Y_1_2', 'Y_1_3', 'Y_2_1')
This might be useful:

Sajid Afaque
Sajid Afaque on 30 Jun 2022
one more simple solution without any extra line, just interchange 2 lines
figure(3), grid on, hold on
X = [1, 2, 3] ;
Y_1 = [ 1, 2, 3 ; 6, 4, 2 ; 1, 7, 4 ];
Y_2 = [ 10, 12, 21];
bar(X , Y_1(: ,1 : 3)');
yyaxis left
yyaxis right
plot(X , Y_2(:, 1 : 3 ),'-o');
legend('Y_1_1', 'Y_1_2', 'Y_1_3', 'Y_2_1')

Categories

Find more on 2-D and 3-D Plots in Help Center and File Exchange

Products


Release

R2021b

Community Treasure Hunt

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

Start Hunting!