Search code examples
matlabplotbar-chartaxisaxes

MATLAB: a better way to switch between primary and secondary y-axis?


I'm aware of plotyy but in my opinion it's not as intuitive as for example typing subplot(2,3,1) and from that point one working in that particular subplot's environment...

Suppose I have the following data:

a=rand(20,1);
a_cumul=cumsum(a);

I would like to do a plot of a_cumul on the primary (left hand) y-axis and a bar chart of a on the secondary (right hand) y-axis.

I'm well aware that I can do:

plotyy(1:length(a_cumul),a_cumul,1:length(a),a,'plot','bar')

But this is cumbersome and what if I want to for example plot to the secondary y-axis only and not plot to the primary y-axis? In short, I'm looking for whether a solution like this exists:

figure;
switchToPrimaryYAxis; % What to do here??
plot(a_cumul);
% Do some formatting here if needed...
switchToSecondaryYAxis; % What to do here??
bar(a);

Thanks a lot for your help!


Solution

  • Basically plotyy:

    • creates two superimposed axes

    • plots the data specified as the first two params on the first axes

    • plots the data specified as the last two params on the second axes

    • set the second second axes color to none making it "transparent" so allowing seeing the graph on the first axes

    • moves the yaxislocation from the standard position (left) to right

    You can create a figure, then two axes make make any plot on the two axes by selecting then with axes(h) where h is the handler of the axes.

    Then you can write a your own function performing the axes adjustment.

    Script to create figure, axes and call the function to adjust the axes

    % Generate example data
    t1=0:.1:2*pi;
    t2=0:.1:4*pi;
    y1=sin(t1);
    y2=cos(t2);
    % Create a "figure"
    figure
    % Create two axes
    a1=axes
    a2=axes
    % Set the first axes as current axes
    axes(a1)
    % Plot something
    plot(t1,y1,'k','linewidth',2)
    % Set the second axes as current axes
    axes(a2)
    % Plot something
    plot(t2,y2,'b','linewidth',2)
    grid
    % Adjust the axes:
    my_plotyy(a1,a2)
    

    Function to adjust the axes - emulating plotyy behaviour

    The function requires, as input, the handles of the two axes

    function my_plotyy(a1,a2)
    
    set(a1,'ycolor',[0 0 0])
    set(a1,'box','on')
    % Adjust the second axes:
    %    change x and y axis color
    %    move x and y axis location
    %    set axes color to none (this make it transparend allowing seeing the
    %       graph on the first axes
    
    set(a2,'ycolor','b')
    set(a2,'xcolor','b')
    set(a2,'YAxisLocation','right')
    set(a2,'XAxisLocation','top')
    set(a2,'color','none')
    set(a2,'box','off')
    

    enter image description here

    Hope this helps.