关于Matlab:绘制顶轴(框)线

Drawing the top axis (box) line

我有一个包含两条线和两个不同的x轴(不同数据单位)的图,如下图所示。

我的问题是我也想(水平)将框的顶部绘制为黑色,而不是像现在一样将其"打开"。 如果该线也具有x轴刻度线,并且与底部水平轴线相同,那就太好了。

显然,grid on不起作用,因为它在右侧绘制了y1轴刻度,在左侧绘制了y2轴刻度,这是我不希望的。

另外,我认为在Matlab 2014中,此方法有效:set(ax(2),'XAxisLocation','top','XTickLabel',[]);,但在Matlab 2015a中不再适用。

例子如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
figure(1);
x = [0, 1, 2, 3];
y_1 = [3, 2, 1.5, 1];
y_2 = [0, 0.5, 0.7, 0.9];
parula_blue = [0, 0.447, 0.741]; parula_red = [0.85, 0.325, 0.098];

[ax, h1, h2] = plotyy(x, y_1, x, y_2);
set(get(ax(1),'Ylabel'),'String','Data 1', 'Color', 'k');
set(h1,'LineWidth',2,'LineStyle','-','Color',parula_blue,'DisplayName', 'Name 1');
set(ax(1),'ycolor',parula_blue);
set(ax(1), 'YTick', [0 1 2 3 4]);
set(ax(1), 'ylim', [0 4]);

set(get(ax(2),'Ylabel'),'String','Data 2', 'Color', 'k');
set(h2,'LineWidth',2,'LineStyle','--','Color',parula_red,'DisplayName','Name 2');
set(ax(2),'ycolor',parula_red);
set(ax(2),'YDir','reverse');
set(ax(2), 'YTick', [0 0.2 0.4 0.6 0.8 1]);

xlabel('X axis desc')
legend('show')
set(ax, 'XTick', x)

set(ax(1),'Box','off') % Turn off box of axis 1, which removes its right-hand ticks
set(ax(2),'Box','off') % Turn off box of axis 2, which removes its left-hand   ticks

enter image description here


根据此答案,您可以简单地向图中添加另一个axes,并指定其水平轴位于顶部(此代码位于代码的末尾):

1
2
hBox = axes('xlim', [x(1) x(end)],'XTick', x, 'YTick',[],'XAxisLocation', 'top',...
            'XTickLabel',[]);

编辑:

根据评论中OP的说明,可以通过对图的子级进行重新排序来绘制黑色轴"蓝色/橙色下方",即在我上面的代码之后,还添加:

1
2
3
uistack(hBox,'bottom'); %// This sends the black axes to the back.
ax(1).Color = 'none';   %// This makes the plot area transparent for the top axes, so
                        %// that ticks belonging to the black axes are visible.

enter image description here

顺便说一句,当我想使用具有不同颜色的次要和主要网格线时,我记得使用类似的技巧-每组网格线都属于自己的轴,具有自己的color


如果要避免添加另一组axes,则仍可以使用ax(2),但需要首先使其可见:

1
2
3
4
5
6
ax(1).Box = 'off';
ax(2).Box = 'off';
ax(2).XAxis.Visible = 'on';
ax(2).XAxisLocation = 'top';
ax(2).XTickLabel = [];
ax(2).XTick = ax(1).XTick ;