Plots: aligning categorical y-axis labels

11 views (last 30 days)
Hi Everyone,
I'm trying to plot a set of error bars with corresponding, categorical labels shown on the right-side (Y2) axis:
% create dummy data
y = [1,2,3];
x = [5,10,20];
err = 0.5*ones(size(y));
% draw plot
figure(1)
yyaxis right
errorbar(x,y,err,'.b','horizontal')
xlim([0 30])
ylim([0 4])
% hide Y1 axis
hax = gca;
hax.YAxis(1).Visible='off';
% add categorical labels to Y2 axis
hax.YAxis(2).TickLabels = {'Label one','Label two','Label three'};
Instead of repeated Y2 labels of 'Label one', 'Label two', 'Label three' I would like each label to be used once - opposite each of the error bars. That is at the positions specified by y.
Any help with this would be much appreciated! Many thanks.

Accepted Answer

Les Beckham
Les Beckham on 4 Dec 2023
% create dummy data
y = [1,2,3];
x = [5,10,20];
err = 0.5*ones(size(y));
% draw plot
figure(1)
yyaxis right
errorbar(x,y,err,'.b','horizontal')
xlim([0 30])
ylim([0 4])
% hide Y1 axis
hax = gca;
hax.YAxis(1).Visible='off';
% add categorical labels to Y2 axis
hax.YAxis(2).TickValues = y; %<<<< Add this to specify where the ticks (and hence the labels) are located
hax.YAxis(2).TickLabels = {'Label one','Label two','Label three'};

More Answers (1)

Dyuman Joshi
Dyuman Joshi on 4 Dec 2023
Set the yticks using the values in y and modify the yticklabels of the right y-axis accordingly -
If the order of labels is expected to be reverse of that is displayed below, flip the variable str to reverse the order.
% create dummy data
y = [1,2,3];
x = [5,10,20];
err = 0.5*ones(size(y));
% draw plot
figure(1)
yyaxis right
errorbar(x,y,err,'.b','horizontal')
yticks(y)
str = {'Label one','Label two','Label three'};
yticklabels(str)
xlim([0 30])
ylim([0 4])
% hide Y1 axis
hax = gca;
hax.YAxis(1).Visible='off';
  2 Comments
John Wills
John Wills on 5 Dec 2023
Thanks Dyuman - really appreciate the help. Best wishes

Sign in to comment.

Products


Release

R2022b

Community Treasure Hunt

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

Start Hunting!