Plots: aligning categorical y-axis labels

9 次查看(过去 30 天)
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.

采纳的回答

Les Beckham
Les Beckham 2023-12-4
% 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'};

更多回答(1 个)

Dyuman Joshi
Dyuman Joshi 2023-12-4
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';

类别

Help CenterFile Exchange 中查找有关 Grid Lines, Tick Values, and Labels 的更多信息

产品


版本

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by