如何标记 y 轴上的位置?

How to label a position on y axis?

如上图所示,我想在y轴上标记两个位置为"y=60"和"y=-60"。

我尝试将命令执行为

yticks([-60 0 60]);
yticklabels({'y = -60','y = 0','y = 60'})

然而,它显示"there is no variable yticks"。此外,我还想将刻度添加到 y 轴,如 [-60 -40 -20 0 20 40 60].

你可以这样做

scatter(0:5,0:5+rand(5,1))

yticks([0 2.5 5])
set(gca,'YTickLabel',{'y=0', 'y=2.5', 'y=5'})

yticks and yticklabels 在 MATLAB 2016b 中引入。

对于早期版本,要在当前 y 刻度的同时添加额外的 y 刻度,并像问题中那样更改 y 刻度标签,您可以使用:

set(gca, 'YTick', unique([-60, 60, get(gca, 'YTick')]));
%-60 and 60 are the additional ticks that'll be added to y axis.
%unique is applied just in case if the tick/s, that we want to add, already exist/s 
%and to sort the array in ascending order. unique also does the sorting in ascending order
%if you want to show only specific yticks, use the following instead:
%set(gca,'YTick',[-60 -40 -20 0 20 40 60]); %to show only [-60 -40 -20 0 20 40 60] yticks
temp1=get(gca,'Yticklabels');  %Getting Yticklabels
temp2=str2double(temp1);       %Converting them to double
%Searching for desired labels and concatenating them with 'y = '
temp1(temp2==-60|temp2==60)= strcat({'y = '},{'-60','60'}); 
set(gca,'YTickLabel',temp1);   %Setting the Yticklabels