Sunday, January 7, 2018

Change Color of the Second Y-axis using YYAXIS in MATLAB


If you want to plot the axes themselves in different colors, here's an example that just works. You can copy and paste the code into Matlab and tinker. What I figured out is that you need to get the gca object and modify the relevant parameters.

XX = 1:10;
YY1 = rand(10,1);
YY2 = rand(10,1);
subplot(3,3,6);  % I'm doing a figure with subplot, but "figure" would work too
yyaxis left;
plot(XX,YY1,'k');
ax = gca;
ax.YAxis(1).Color = 'k';
yyaxis right;
plot(XX,YY2,'r');
ax.YAxis(2).Color = 'r';

And in case you need a reminder of the basic color coding:

           b     blue          .     point              -     solid
           g     green         o     circle             :     dotted
           r     red           x     x-mark             -.    dashdot
           c     cyan          +     plus               --    dashed  
           m     magenta       *     star             (none)  no line
           y     yellow        s     square
           k     black         d     diamond
           w     white         v     triangle (down)
                               ^     triangle (up)
                               <     triangle (left)
                               >     triangle (right)
                               p     pentagram
                               h     hexagram 


This took a while to figure out. I came across the following unanswered stackoverflow.com post (https://stackoverflow.com/questions/45758444/change-color-of-the-second-y-axis-in-the-matlab-using-new-yyaxis-tool) that helped.