Moving MATLAB axis ticks by a half step

半城伤御伤魂 提交于 2019-12-04 09:49:03

You need to move the ticks, but get the labels before and write them back after moving:

f = figure(1)
X = randi(10,10,10);
surf(X)
view(0,90)

ax = gca;
XTick = get(ax, 'XTick')
XTickLabel = get(ax, 'XTickLabel')
set(ax,'XTick',XTick+0.5)
set(ax,'XTickLabel',XTickLabel)

YTick = get(ax, 'YTick')
YTickLabel = get(ax, 'YTickLabel')
set(ax,'YTick',YTick+0.5)
set(ax,'YTickLabel',YTickLabel)


Or if you know everything before, do it manually from the beginning:

[N,M] = size(X)

set(ax,'XTick',0.5+1:N)
set(ax,'XTickLabel',1:N)
set(ax,'YTick',0.5+1:M)
set(ax,'YTickLabel',1:M)

The marked answer works with a surf or mesh plot, however, I needed a solution which worked for a 2d plot. This can be done by creating two axes, one to display the grid and the other to display the labels as follows

xlabels=1:1:10;                               %define where we want to see the labels
xgrid=0.5:1:10.5;                             %define where we want to see the grid  

plot(xlabels,xlabels.^2);                     %plot a parabola as an example
set(gca,'xlim',[min(xgrid) max(xgrid)]);      %set axis limits so we can see all the grid lines
set(gca,'XTickLabel',xlabels);                %print the labels on this axis

axis2=copyobj(gca,gcf);                       %make an identical copy of the current axis and add it to the current figure
set(axis2,'Color','none');                    %make the new axis transparent so we can see the plot
set(axis2,'xtick',xgrid,'XTickLabel','');     %set the tick marks to the grid, turning off labels
grid(axis2,'on');                             %turn on the grid

This script displays the following figure :

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!