How do you label every other tick?

171 views (last 30 days)
FINNSTAR7
FINNSTAR7 on 28 Mar 2018
Edited: FINNSTAR7 on 29 May 2021
I'm trying to scatter plot some data and would like to know how to label only every other 'x' tick. I've been using xticks and xticklabels, but to no avail. This is the part of my code that produces the plot in MATLAB R2017a:
scatter(x_vals,y_vals,[],c); xlim([n x_max]);
xticks(n:1:x_max); % xticklabels(n:x:x_max); I'm aware this is not proper xticklabels syntax,
% I just wrote it this way to show what I wanted.
hold on
vline(average,'b',sprintf(['Average\n(' num2str(average) ')']));
Which for some specific data may look like this:
So is there a way to still have every tick mark show while only having every second or third tick mark labeled? Like in the case above, keep every tick mark, but only have labels "3, 6, 9,[...], 27". Keep in mind the data that is plotted will change, so manually inputting xticklabels({'blah', ' ', 'blah' , ' ', 'blah', etc...}) each time won't work for me.
I've tried looking around for questions like mine but I kept seeing things like "set(gca,...", which is both something I've never seen and wasn't able to get to work. I'm somewhat new to MatLab and I'm not familiar with a whole lot (had to research most of this above code too), so you might have to dumb your answers down for me, sorry :P

Accepted Answer

Sean de Wolski
Sean de Wolski on 28 Mar 2018
Something along these lines:
plot(1:10);
ax = gca;
labels = string(ax.XAxis.TickLabels); % extract
labels(2:2:end) = nan; % remove every other one
ax.XAxis.TickLabels = labels; % set
  3 Comments
Sean de Wolski
Sean de Wolski on 28 Mar 2018
You probably just need to upgrade. I'm on 18a and it works fine.
In lieu of upgrading, you could probably convert back to cellstr(labels) on the right-hand side of the last line.
FINNSTAR7
FINNSTAR7 on 28 Mar 2018
Edited: FINNSTAR7 on 29 Mar 2018
Ah, found what I was looking for.
scatter(x_vals,y_vals,[],c); xlim([n x_max]);
xticks(n:1:x_max); ax = gca;
labels = string(ax.XAxis.TickLabels);
for i=1:n-1
labels(i+1:n:x_max-n) = ' ';
end
ax.XAxis.TickLabels = labels;
So the main issue was the " nan" stuff, as it didn't like <missing > in a string for NumericRuler (or something like that). So just blanking them like this: labels(i+1:n:x_max-n) = ' '; got rid of the error mentioned above.
You'll also notice I stuck the labels stuff in a for loop as well. Doing this allows me to not just blank every other label, but every two, three, four, etc. labels, depending on how far out my data goes. Like in the above picture, the ticks are now only labeled every 3 intervals including the first and last tick.
Thank you so much for the help! My plots will look much cleaner with this.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!