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

17 visualizaciones (últimos 30 días)
승현 이
승현 이 el 30 de Jun. de 2022
Respondida: Sajid Afaque el 30 de Jun. de 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!

Respuesta aceptada

Garmit Pant
Garmit Pant el 30 de Jun. de 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')

Más respuestas (3)

KSSV
KSSV el 30 de Jun. de 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 el 30 de Jun. de 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 el 30 de Jun. de 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')

Categorías

Más información sobre 2-D and 3-D Plots en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by