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

15 次查看(过去 30 天)
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!

采纳的回答

Garmit Pant
Garmit Pant 2022-6-30
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')

更多回答(3 个)

KSSV
KSSV 2022-6-30
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 2022-6-30
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 2022-6-30
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')

类别

Help CenterFile Exchange 中查找有关 2-D and 3-D Plots 的更多信息

产品


版本

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by