Plot line-chart on the left axis uper the bar-chart on the right axis

后端 未结 3 1039
我在风中等你
我在风中等你 2020-12-11 21:27

In a graph with two y axis, one for a line plot (left) and one for a bar-chart (right), I would like that the bar-chart get under the line chart for a better visibility inst

3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-11 22:33

    This is actually a really great question because there is really no clearly documented way of doing this and in all examples, whatever is on the right axes is displayed on top. Even in this example on their own website, notice how careful they are to plot the bar on the left axes.

    So as a preface, yyaxis does not create a separate axes (as yyplot used to), but rather just applies an additional NumericRuler to the same axes. If it were simply different axes we could use uistack to re-order the axes in any way we want, but because they are the same axes, we need to look a little closer at the axes properties which control the z-ordering of the contents.

    When we look at these properties, yyaxis automatically changes the SortMethod of the axes to children from it's default value of depth. This makes any object which appears in the left axes to be below anything added to the right axes. So all we need to do to fix this, is to change the SortMethod back to the default value (depth) and then the ordering will be dependent upon z position like it normally would within an axes.

    So as a demonstration, let's create some data

    days = 0:5:35;
    conc = [515 420 370 250 135 120 60 20];
    temp = [29 23 27 25 20 23 23 17];
    

    Create the plots just like you did (a line and a bar with the bar on the right)

    yyaxis right
    b = bar(days, temp, 'FaceColor', [0.8 0.8 0.8]);
    yyaxis left
    p = plot(days, conc, 'LineWidth', 2);
    

    And now if we change the SortMethod it brings the line object on top.

    set(gca, 'SortMethod', 'depth')
    

提交回复
热议问题