Search code examples
matlabplotmatlab-figureaxis-labels

How to label a position on y axis?


enter image description here

As depicted in the figure above, I want to label two positions on y axis as "y=60" and "y=-60".

I try to implement the command as

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

However, it reveals that "there is no variable yticks". Additionally, I also want to add ticks to y axis as [-60 -40 -20 0 20 40 60].


Solution

  • yticks and yticklabels were introduced in MATLAB 2016b.

    For earlier versions, to add additional y-ticks alongwith the current y-ticks, and change y-tick labels like those in the question, you can use this:

    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