将MATLAB轴标签移动半个步长

4
我试图将MATLAB的刻度线与我的网格对齐,但我找不到一个好的方法来偏移标签。
另外,如果我运行set(gca,'XTickLabel',1:10),我的x轴刻度标签最终会从1到5。发生了什么事?

你用什么来绘图?是pcolor吗?如果你使用imagesc,对齐就如你所期望的那样。(在图形上使用'axis xy'将轴翻转,使得y值从下往上增加。)额外的好处是,它不会剪切你的数据的最后一行/列。由于我可以看到在(10,3)处有一个正方形的边界,所以我猜测有些东西被剪切了。 - craq
2个回答

7
你需要移动刻度,但在移动之前获取标签,并在移动后将其写回:
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)

在此输入图片描述


或者,如果您已经了解所有内容,请从头开始手动操作:

[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)

完美的答案。谢谢! - Nick Sweet

0
标记的答案适用于 surf 或 mesh 图形,然而我需要一个适用于 2D 图形的解决方案。这可以通过创建两个轴来实现,一个用于显示网格,另一个用于显示标签,如下所示。
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

这个脚本显示以下图形:

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接