Search code examples
matlabplotmatlab-figure

3 x-axis in matlab plot?


I need to plot a figure with 3 x-axes. Each axis is linked to the other by a mathematical formula. I want to do this because the x value can be seen as wavelength [nm], velocity [m/s] or energy [eV] and I want the reader to not have to convert it themselves on each graph.

I searched online and only found something for 2 x-axes, but no more.

Edit: I am using version R2011a.

So it should look like this, which I (obviously) didn't create in MATLAB:

What I 'd like to plot (it is not done on matlab this one...)

Thanks in advance!


Solution

  • As shown in this answer, you can create a new axes object with near-zero height, so that it is essentially just the x-axis. Be aware that all actual plots must be done on the first axes as this is the area you can see!

    Demo code:

    % Create some plotting data and plot
    x = 0:0.1:2*pi;   y = sin(x);
    % Plot, can specify line attributes (like LineWidth) either 
    % - inline: plot(x,y,'linewidth',2)
    % - after: p1 = plot(x,y); p1.LineWidth = 2;
    plot(x,y);
    % Get current axes object (just plotted on) and its position
    ax1 = gca;
    axPos = ax1.Position;
    % Change the position of ax1 to make room for extra axes
    % format is [left bottom width height], so moving up and making shorter here...
    ax1.Position = axPos + [0 0.3 0 -0.3];
    % Exactly the same as for plots (above), axes LineWidth can be changed inline or after
    ax1.LineWidth = 2;
    % Add two more axes objects, with small multiplier for height, and offset for bottom
    ax2 = axes('position', (axPos .* [1 1 1 1e-3]) + [0 0.15 0 0], 'color', 'none', 'linewidth', 2);
    ax3 = axes('position', (axPos .* [1 1 1 1e-3]) + [0 0.00 0 0], 'color', 'none', 'linewidth', 2);
    % You can change the limits of the new axes using XLim
    ax2.XLim = [0 10];
    ax3.XLim = [100 157];
    % You can label the axes using XLabel.String
    ax1.XLabel.String = 'Lambda [nm]';
    ax2.XLabel.String = 'Velocity [m/s]';
    ax3.XLabel.String = 'Energy [eV]';
    

    Output:

    multiple x axes matlab


    Edit:
    Before the 2014b graphics changes you will need to make a couple of tweaks for getting and setting axes properties. The equivalent code would more heavily use the set command, and look something like this:

    x = 0:0.1:2*pi;   y = sin(x);
    plot(x,y);
    ax1 = findobj(gca, 'type', 'axes')
    axPos = get(ax1, 'Position');
    set(ax1, 'Position', axPos + [0 0.3 0 -0.3]);
    set(ax1, 'LineWidth', 2);
    ax2 = axes('position', (axPos .* [1 1 1 1e-3]) + [0 0.15 0 0], 'color', 'none', 'linewidth', 2);
    ax3 = axes('position', (axPos .* [1 1 1 1e-3]) + [0 0.00 0 0], 'color', 'none', 'linewidth', 2);
    set(ax2, 'xlim', [0 10]);
    set(ax3, 'xlim', [100 157]);
    axes(ax1); xlabel('Lambda [nm]');
    axes(ax2); xlabel('Velocity [m/s]');
    axes(ax3); xlabel('Energy [eV]');