【问题标题】:MATLAB: a better way to switch between primary and secondary y-axis?MATLAB:在主要和次要 y 轴之间切换的更好方法?
【发布时间】:2015-12-01 02:32:55
【问题描述】:

我知道plotyy,但在我看来,它不像输入subplot(2,3,1) 那样直观,从那时起,在该特定子图的环境中工作...

假设我有以下数据:

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

我想在主要(左侧)y 轴上绘制 plota_cumul,在次要(右侧)y 轴上绘制 a 条形图。

我很清楚我可以做到:

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

但这很麻烦,如果我只想绘制到辅助 y 轴而不绘制到主 y 轴怎么办?简而言之,我正在寻找这样的解决方案是否存在:

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

非常感谢您的帮助!

【问题讨论】:

    标签: matlab plot bar-chart axis axes


    【解决方案1】:

    基本上plotyy:

    • 创建两个叠加的axes

    • 在第一个轴上绘制指定为前两个参数的数据

    • 在第二个轴上绘制指定为最后两个参数的数据

    • 将第二个第二轴颜色设置为 none 使其“透明”,以便查看第一个轴上的图形

    • yaxislocation从标准位置(左)移到右

    您可以创建一个figure,然后通过使用axes(h) 选择then,在两个axes 上创建两个axes,其中h 是轴的处理程序。

    然后您可以编写自己的函数来执行轴调整。

    脚本创建figureaxes并调用函数调整坐标轴

    % 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 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')
    

    希望这会有所帮助。

    【讨论】:

    • 非常感谢,这正是我想要的!我很感激。
    猜你喜欢
    • 1970-01-01
    • 2021-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多