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

Walter Roberson
Walter Roberson 2019년 12월 9일
Yes, it is possible. However, it is a nuisance at the best of times, and gets to be a pain if any text anywhere on your plot is using tex or latex interpreter.
It is a lot easier to just examine the current ylim() and make it a bit larger, such as giving an extra 5%. This simplistic solution does not take into account that there might be existing text that is notably off-screen: it makes no attempt to locate the text objects and figure out if they are visible and fontsize and vertical alignment and complications caused by tex or latex interpreters... but for the case you give the example for, making ylim just a bit larger is very likely to be good enough.
Davor Pavlovski
Davor Pavlovski 2019년 12월 9일
yes I thought about that, but i just wondered if there is a cleaner way
Walter Roberson
Walter Roberson 2019년 12월 9일
The only methods I can think of are not clean.

댓글을 달려면 로그인하십시오.

 채택된 답변

Adam Danz
Adam Danz 2019년 12월 9일
편집: Adam Danz 2019년 12월 9일

1 개 추천

  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

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

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Graphics Object Properties에 대해 자세히 알아보기

제품

릴리스

R2019a

질문:

2019년 12월 9일

편집:

2019년 12월 9일

Community Treasure Hunt

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

Start Hunting!

Translated by