Create an xy plot with two y axis

前端 未结 2 887
囚心锁ツ
囚心锁ツ 2020-12-04 01:27

I have the following code. I\'m trying to create an xy plot wth two y axis. However I only get one line down the middle. I want y to be the vertical axis to the right and ve

相关标签:
2条回答
  • 2020-12-04 01:56

    One option is plotyy()

    x = 1:10;
    y = rand(1,10);
    plotyy(x, x, x, y)
    

    A more flexible option is to overlay two (or more) axes and specify what data you want plotted on each.

    % Sample data
    x = 1:10;
    y = rand(1,10);
    
    % Create axes & store handles
    h.myfig = figure;
    h.ax1 = axes('Parent', h.myfig, 'Box', 'off');
    h.ax2 = axes('Parent', h.myfig, 'Position', h.ax1.Position, 'Color', 'none', 'YAxisLocation', 'Right');
    
    % Preserve axes formatting
    hold(h.ax1, 'on');
    hold(h.ax2, 'on');
    
    % Plot data
    plot(h.ax1, x, x);
    plot(h.ax2, x, y);
    

    The Box property turns off drawing of the external box around each axis. I'd recommend turning it off for all but one of the axes to eliminate axis tick clutter.

    The Position property sets the axis size and position to the exact same as the first axis. Note that I've used the dot notation introduced in R2014b, if you have an older version just swap h.ax1.Position with get(h.ax1, 'Position').

    The Color and YAxisLocation calls should be self explanatory.

    I used hold to preserve the axes formatting. If you don't include these and plot your data it will reset the background color and axes locations, requiring you to adjust them back.

    Hope this helps!

    0 讨论(0)
  • 2020-12-04 02:08

    Starting from Matlab 2016a you can also use new function yyaxis. Example from documentation:

    x = linspace(0,10);
    y = sin(3*x);
    yyaxis left
    plot(x,y)
    
    z = sin(3*x).*exp(0.5*x);
    yyaxis right
    plot(x,z)
    ylim([-150 150])
    

    Resulting image

    0 讨论(0)
提交回复
热议问题