Question

I'm trying to position MATLAB's ticks to line up with my grid, but I can't find a good way to offset the labels.

Also, if I run set(gca,'XTickLabel',1:10), my x tick labels end up ranging from 1 to 5. What gives?

enter image description here

Was it helpful?

Solution

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)

enter image description here


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)

OTHER TIPS

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 :

enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top