Resize plot to fit text

34 views (last 30 days)
Davor Pavlovski
Davor Pavlovski on 9 Dec 2019
Edited: Adam Danz on 9 Dec 2019
Is it possible to resize the y-axis automatically, so that my text always fits in the plot.
(as far as I can see, it is not clearly possible by using the "axis" and "ylim" functions)
Capture.PNG
  3 Comments
Davor Pavlovski
Davor Pavlovski on 9 Dec 2019
yes I thought about that, but i just wondered if there is a cleaner way
Walter Roberson
Walter Roberson on 9 Dec 2019
The only methods I can think of are not clean.

Sign in to comment.

Accepted Answer

Adam Danz
Adam Danz on 9 Dec 2019
Edited: Adam Danz on 9 Dec 2019
  1. Get the extent of the text objects after plotting the text.
  2. Add the vertical position and height to get the upper position of each text object
  3. Adjust the y axis limit so it contains all text objects.
h = text(1:numel(y),y,strsplit(num2str(y)),'VerticalAlignment','bottom');
ext = cell2mat(get(h,'Extent')); % Step 1
upperPosition = sum(ext(:,[2,4]),2); % Step 2
ylim([min(ylim()),max(max(ylim()),max(upperPosition))]) % step 3
The y limit will be adjusted so that it maintains its current lower limit and increases its upper limit only if there is text that exceeds the axis boundaries.
Result
[update]
That could be reduced to one line where h is the handle to the text output.
ylim([min(ylim()), max(max(ylim()),max(cellfun(@(x)sum(x([2,4])),get(h,'Extent'))))])
It could also be put into an anonymous function where the two inputs are h and ax which are the text handles and the axis handle.
fitText = @(ax,h)ylim(ax,[min(ylim(ax)), max(max(ylim(ax)),max(cellfun(@(x)sum(x([2,4])),get(h,'Extent'))))]);
fitText(gca,h)
  1 Comment
Adam Danz
Adam Danz on 9 Dec 2019
The full code to produce the figure, text and y limits:
clf()
y = [1.6, 1.7, 2];
bar(y)
axis tight
h = text(1:numel(y),y,strsplit(num2str(y)),'VerticalAlignment','bottom');
ext = cell2mat(get(h,'Extent')); % Step 1
upperPosition = sum(ext(:,[2,4]),2); % Step 2
ylim([min(ylim()),max(max(ylim()),max(upperPosition))]) % step 3

Sign in to comment.

More Answers (0)

Products


Release

R2019a

Community Treasure Hunt

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

Start Hunting!