首页 文章

如何在Matlab中插入两个X轴图

提问于
浏览
12

我想用相同的图创建一个带有双X轴(m / s和km / h)的Matlab图形 .

我发现了plotyy和 - 在Matlab的重复性 - plotyyy,但我正在寻找:

  • 双X轴 .

  • 在情节下面一起 .

我的代码非常简单:

stem(M(:, 1) .* 3.6, M(:, 3));

grid on

xlabel('Speed (km/h)');
ylabel('Samples');

M(:, 1) 是速度(以m / s为单位), M(:, 3) 是数据 .

我想在底部只有第二条线,速度以m / s为单位 .

3 回答

  • -1

    您可以执行以下操作 . 与@ Benoit_11的解决方案相比,我使用普通的Matlab标签,并使用句柄引用两个轴,因此分配是明确的 .

    Example Plot

    以下代码创建一个空的x轴 b ,单位为m / s,高度可忽略不计 . 在此之后,实际绘图将在第二个轴 a 中绘制,该轴位于其他轴上方并且以km / h为单位 . 要在特定轴上绘图,请插入axes-handle作为 stem 的第一个参数 . 从m / s到km / h的转换直接写入 stem 的调用中 . 最后,需要将两个轴的 xlim -property设置为相同的值 .

    % experimental data
    M(:,1) = [ 0,  1,  2,  3,  4,  5];
    M(:,3) = [12, 10, 15, 12, 11, 13];
    
    % get bounds
    xmaxa = max(M(:,1))*3.6;    % km/h
    xmaxb = max(M(:,1));        % m/s
    
    
    figure;
    
    % axis for m/s
    b=axes('Position',[.1 .1 .8 1e-12]);
    set(b,'Units','normalized');
    set(b,'Color','none');
    
    % axis for km/h with stem-plot
    a=axes('Position',[.1 .2 .8 .7]);
    set(a,'Units','normalized');
    stem(a,M(:,1).*3.6, M(:,3));
    
    % set limits and labels
    set(a,'xlim',[0 xmaxa]);
    set(b,'xlim',[0 xmaxb]);
    xlabel(a,'Speed (km/h)')
    xlabel(b,'Speed (m/s)')
    ylabel(a,'Samples');
    title(a,'Double x-axis plot');
    
  • 7

    作为一个非常简单的替代方案,您还可以创建第二个轴(透明)并将其放在第一个轴下方,这样您只能看到x轴 .

    例:

    clear
    clc
    close all
    
    x = 1:10;
    
    x2 = x/3.6;
    
    y = rand(size(x));
    
    hP1 = plot(x,y);
    
    a1Pos = get(gca,'Position');
    
    %// Place axis 2 below the 1st.
    ax2 = axes('Position',[a1Pos(1) a1Pos(2)-.05 a1Pos(3) a1Pos(4)],'Color','none','YTick',[],'YTickLabel',[]);
    
    %// Adjust limits
    xlim([min(x2(:)) max(x2(:))])
    
    text(2.85,0 ,'m/s','FontSize',14,'Color','r')
    text(2.85,.05 ,'km/h','FontSize',14,'Color','r')
    

    输出:

    enter image description here

    然后,您可以手动为每个单元添加不同颜色的x标签,例如 .

  • 16

    我能想到的最好方法是使用2个图,例如,你可以通过这样的方式将图分割成大小部分:

    subplot(100, 1, 1:99) // plot your graph as you normally would
    plot(...
    
    subplot(100, 1, 100) // Plot a really small plot to get the axis
    plot(...)
    b = axis()
    axis([b(1:2), 0, 0]) // set the y axis to really small
    

    这是未经测试的,你可能需要摆弄一下,但它应该有希望让你走上正确的轨道 .

相关问题