问题描述:想把下面左图matlab默认的方框刻度绘制成右图box off刻度在外面的效果。(只显示纵坐标的坐标线为灰色,X坐标轴不变,y轴的lable也不会随着y轴的grid改变。主要看坐标轴的变化,因为这里线条是随机的,每次都不一样!)
实现代码:
function [ ] = gridLine( )
%绘制一条随机,浅蓝色,粗细为3像素的线条
plot(11:20, rand(10,1)*5,'color',[0 0.6 1],'LineWidth',3)
%get a handle to first axis
hAx1 = gca;
%create a second transparent axis, same position/extents, same ticks and labels
hAx2 = axes('Position',get(hAx1,'Position'), ...
'Color','none', 'Box','off', ...
'XTickLabel',get(hAx1,'XTickLabel'), 'YTickLabel',get(hAx1,'YTickLabel'), ...
'XTick',get(hAx1,'XTick'), 'YTick',get(hAx1,'YTick'), ...
'XLim',get(hAx1,'XLim'), 'YLim',get(hAx1,'YLim'));
%show grid-lines of Y axis, give them desired color (light gray), but hide text labels
set(hAx1,'YColor',[136 136 136]/255,'YGrid','on','GridLineStyle','-','XTickLabel',[], 'YTickLabel',[], 'Box','off');
%hidden the XTick but keep the XTickLabel on axes1.
set(hAx1, 'TickLength', [0 0]);
%this is another way instead of the two lines above.
%set(hAx1,'YColor',[136 136 136]/255,'YGrid','on','GridLineStyle','-','XTickLabel',[], 'YTickLabel',[], 'Box','off', 'XTick',[]); %this also work!
%将刻度显示在框外面
set(hAx2,'TickDir','Out')
end
如果只是简单的用如下代码:
function [ ] = gridLine( )
%绘制一条随机,浅蓝色,粗细为3像素的线条
plot(11:20, rand(10,1)*5,'color',[0 0.6 1],'LineWidth',3)
set(gca,'YGrid','on','YColor','r');
%将刻度显示在框外面
set(gca,'TickDir','Out')
end效果会是下图的样子:(整个纵坐标(刻度,lable,坐标线)都会一起变化,因为它们在matlab里面是一个整体!当然,窗口内部的纵坐标的网格线可以用上面一样的属性【'GridLineStyle','-'】从默认的dash设置为solid。)
参考文献:
http://stackoverflow.com/questions/6580274/minor-grid-with-solid-lines-grey-color
http://stackoverflow.com/questions/15529585/remove-xticks-but-keep-xticklabels-in-matlab
http://www.mathworks.com/matlabcentral/answers/74260-xtick-visibility-off-with-xticklabel-showing
本文介绍了如何在Matlab中实现只对纵坐标添加grid线,同时保持横坐标和刻度不变的效果,即实现坐标轴的box off样式,使y轴的label不随grid变化。通过参考相关文献,提供了实现这一效果的代码。

被折叠的 条评论
为什么被折叠?



