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

17 vues (au cours des 30 derniers jours)
승현 이
승현 이 le 30 Juin 2022
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!

Réponse acceptée

Garmit Pant
Garmit Pant le 30 Juin 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')
  1 commentaire
승현 이
승현 이 le 30 Juin 2022
Thankyou for advice, the problem solved clearly!

Connectez-vous pour commenter.

Plus de réponses (3)

KSSV
KSSV le 30 Juin 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
  1 commentaire
승현 이
승현 이 le 30 Juin 2022
Thankyou for advice, the problem solved clearly!

Connectez-vous pour commenter.


Abhishek Tiwari
Abhishek Tiwari le 30 Juin 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:
  1 commentaire
승현 이
승현 이 le 30 Juin 2022
Thankyou for advice, the problem solved clearly!

Connectez-vous pour commenter.


Sajid Afaque
Sajid Afaque le 30 Juin 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')

Catégories

En savoir plus sur 2-D and 3-D Plots dans Help Center et File Exchange

Produits


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by