How to change y axis label with percentage?
21 views (last 30 days)
Show older comments
I would much appreciate some help with this. I have the code, written below, and I want to change to the y-axis label to be something like yaxis = [-50 0 50 100] and these values in %. I managed to get the y-axis values with percentages but I didn't manage to change to my desired interval. I would like something like the image attached, but with % included. any thoughts?
x = [1,2,3,4,5,6,7,8];
y = [2.8, 3.33, 4.8,2.1,2.5,0.35,3.4,1.6];
figure
plot (x,y,'*');
a = [cellstr(num2str(get(gca,'ytick')'))];%convert y-axis values to percentage values
pct = char(ones(size(a,1),1)*'%');%create a vector of '%' signs
new_yticks = [char(a),pct]; %append the '%' signs after the percentage values
set(gca,'yticklabel',new_yticks) %reflect the changes on the plot
ax = gca;
ax.YGrid = 'on'
xlabel('Patient');
ylabel('Percent Difference');

1 Comment
Jan
on 24 Mar 2018
a = [cellstr(num2str(get(gca,'ytick')'))];
pct = char(ones(size(a,1),1)*'%');
This is much too difficult. There is no need for square brackets in the first line. The 2nd can be simplified: repmat('%', size(a,1), 1).
Accepted Answer
Jan
on 24 Mar 2018
Edited: Jan
on 24 Mar 2018
x = [1,2,3,4,5,6,7,8];
y = [2.8, 3.33, 4.8,2.1,2.5,0.35,3.4,1.6];
figure
ax = axes;
plot (x,y,'*');
set(ax, 'YTick', [-50, 0, 50, 100], 'YLim', [-50, 100]);
ytickformat(ax, 'percentage');
ax.YGrid = 'on'
xlabel('Patient');
ylabel('Percent Difference');
Alternatively:
ytickformat(ax, '%g%%');
0 Comments
More Answers (1)
Star Strider
on 24 Mar 2018
I am not certain what result you want.
Try this:
x = [1,2,3,4,5,6,7,8];
y = [2.8, 3.33, 4.8,2.1,2.5,0.35,3.4,1.6];
figure(1)
plot (x,y,'*');
y_pct_lbl = [-50 0 50 100]; % Desired Labels
yt_orig = get(gca, 'YTick'); % Original Y-Tick Values & Labels
yt_new = linspace(min(yt_orig), max(yt_orig), numel(y_pct_lbl)); % New Y-Tick Values
yt_lbl = regexp(sprintf('%d %%\n', y_pct_lbl), '\n', 'split'); % New Y-Tick Labels
set(gca, 'YTick',yt_new, 'YTickLabel',yt_lbl(1:end-1)) % Change Y-Tick Labels
4 Comments
See Also
Categories
Find more on Labels and Annotations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!