Resizing Figure to Make Room for Title without Resizing Plot
이 질문을 팔로우합니다.
- 팔로우하는 게시물 피드에서 업데이트를 확인할 수 있습니다.
- 정보 수신 기본 설정에 따라 이메일을 받을 수 있습니다.
오류 발생
페이지가 변경되었기 때문에 동작을 완료할 수 없습니다. 업데이트된 상태를 보려면 페이지를 다시 불러오십시오.
이전 댓글 표시
I'm trying to create a figure. I want the plot sizes to remain the same, but I want more room at the top of the figure to display my titles.
How do I accomplish this? I can't simply resize the entire figure, becuase the plot sizes increase too!

채택된 답변
hAx=gca;
hAx.Position=hAx.Position.*[1 1 1 0.95];
adjusts the height of axes to be 95% of default/previous height. Adjust to suit; repeat for each axes.
If you have saved all the axes handles, one could do it globally via set(hAx, ...) get() with some machinations.
댓글 수: 16
in your comment, the first line should be hAx (not Ax), but other than that -- thanks!
+1 Typo corrected.
Ahh, I just noticed now that the lower part gets cut off -- other thoughts?

I can't reproduce that here; the above only reduces the position vector 4th position which is [left bottom width height].
I can cause the upper title to be clipped by increasing 'fontsize' sufficiently, but the above to reduce the axes height serves to provide sufficient room without moving anything below.
Can you post a script that will reproduce the symptoms? Can be just random data...
f1 = figure(1); set(gcf,'Position', [10 10 1450 350])
axFnt = 12; ttlFnt = 20; lblFnt = 13;
for k = 1:3
subplot(1,3,k)
plot([1:300],[1:300])
xlabel('time [ms]','FontSize',lblFnt); ylabel('\Delta S [units]','FontSize',lblFnt);
xlim([0 300]); %ylim([0 .4]);
ttl = title(strcat('A',num2str(k)),'FontSize',ttlFnt);
ttl.Units = 'Normalize';
ttl.Position(1) = 0; % use negative values (ie, -0.1) to move further left
ttl.HorizontalAlignment = 'left';
hAx=gca; hAx.Position=hAx.Position.*[1 1 1 0.95];
end
Order is significant turns out...without digging even further into bowels of what gets munged on when moving the title around and making it bigger than was designed for, the following resulted in what appears to be wanted:
k=1;
hAx(k)=subplot(1,3,k); % save the axes handles when create the object
plot([1:300],[1:300])
xlabel('time [ms]','FontSize',lblFnt); ylabel('\Delta S [units]','FontSize',lblFnt);
hAx(k).Position(4)=hAx.Position(4)*0.95;
hTtl(k)=title(strcat('A',num2str(k)),'FontSize',ttlFnt,'Position',[0 300],'HorizontalAlignment','left');

The key is to create the x-,y-labels BEFORE writing the title and munging on its position grossly while the auto-scaling of the axes position is still operational. Once you write the title and mung on its position, that turns internal scaling off and the axes position stays fixed at the original default which is for smaller fontsize.
You could, of course, also adjust the lower position of the axes (2nd member 'Position' array) to raise it up some programmatically, but this seems to work without having to go through that algebra to calculate the desired position consistent with the height.
I need to resize the figure -- I think this is causing problems, when I comment it out, the font labels look alright
close all; clear all; clc;
f1 = figure(1); set(gcf,'Position', [10 10 1450 350]) %% This resizing is causing problems
axFnt = 12; ttlFnt = 20; lblFnt = 13;
for k = 1:3
hAx(k)=subplot(1,3,k); % save the axes handles when create the object
plot([1:300],[1:300])
xlabel('time [ms]','FontSize',lblFnt); ylabel('\Delta S [units]','FontSize',lblFnt);
hAx(k).Position(4)=hAx(k).Position(4)*0.95;
hTtl(k)=title(strcat('A',num2str(k)),'FontSize',ttlFnt,'Position',[0 300],'HorizontalAlignment','left');
end
All was done here on that figure that produced the above. If your renderer/hardware doesn't, then will have to raise the lower position of the axes and recompute the height to match sufficiently to have more room below.
Or, just go with a slightly smaller fontsize would be the easy way out... :)
sorry i didn't follow, so you weren't able to reproduce the problem with the code I posted?
I got the figure I attached before with the same figure height, yes.
However, you can try something like
f1 = figure(1); set(gcf,'Position', [10 10 1450 350]) %% This resizing is causing problems
axFnt = 12; ttlFnt = 20; lblFnt = 13;
for k = 1:3
hAx(k)=subplot(1,3,k); % save the axes handles when create the object
plot([1:300],[1:300])
xlabel('time [ms]','FontSize',lblFnt); ylabel('\Delta S [units]','FontSize',lblFnt);
hAx(k).Position(4)=hAx(k).Position(4)*0.95;
hTtl(k)=title(strcat('A',num2str(k)),'FontSize',ttlFnt,'Position',[0 300],'HorizontalAlignment','left');
hAx(k).Position(2)=hAx(k).Position(2)+hAx(k).Position(4)*0.05;
end
And see if that helps enough. You may then have to reduce the height a little more, too.
What release of matlab are you using?
I couldn't reproduce the problem in r2020b in any of the examples given.
If you're using r2020b or later, a better way to control the left alignment of the title is by using the TitleHorizontalAlignment property of the axes
ax.TitleHorizontalAlignment = 'left'; % ax is axis handle
I got the effect with R2019b, Adam, although behavior differed between having an existing figure of the given height and rewriting into it even if deleted all axes and started over from that of creating the new figure and writing into it the first time. Why that would be, I have no idea.
thanks both of you -- @dpb I've been using modifications of your last posted code to do a variety of figures! I've just been changing numbers -- but what does the last line in the loop do?
Were so many iterations I'm guessing it is the following line in Q?
hAx(k).Position(2)=hAx(k).Position(2)+hAx(k).Position(4)*0.05;
It's just raising the bottom of the axes a little, adding 5% of the height (the 4th element in position vector) to the second (the bottom location). Remember the position vector is defined as [left bottom width height].
The 5% factor is the complement of the 95% that I used above to reduce the height so the final top location will be almost back to its original location.
In original testing, I didn't see the need to make the adjustment to the bottom position if one reduced the height after creating the labels; then it seemed to adjust the postions adequately for clearance. However, I later discovered behavior is different between creating a new figure and writing into it and in having an existing figure of the same dimensions and rewriting into it, even after one deletes all existing axes from the figure. As noted above, I have no idea why that should be so; clearly something gets munged on internally by the previous plotting that doesn't go back to precisely the same initial conditions as are present when the figure is first created.
It was to fix that last small aberration that I just then raised up the location of the bottom axis a smidge...
Yugarshi Mondal
2021년 2월 27일
편집: Yugarshi Mondal
2021년 2월 27일
Thanks for the explanation!
More than that, I was dumping insets into the figure. The insets were causing additinal consternation -- but they were fixed by modifying the line you mentioned along with the fourth line in the loop!
추가 답변 (0개)
카테고리
도움말 센터 및 File Exchange에서 Creating, Deleting, and Querying Graphics Objects에 대해 자세히 알아보기
제품
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!웹사이트 선택
번역된 콘텐츠를 보고 지역별 이벤트와 혜택을 살펴보려면 웹사이트를 선택하십시오. 현재 계신 지역에 따라 다음 웹사이트를 권장합니다:
또한 다음 목록에서 웹사이트를 선택하실 수도 있습니다.
사이트 성능 최적화 방법
최고의 사이트 성능을 위해 중국 사이트(중국어 또는 영어)를 선택하십시오. 현재 계신 지역에서는 다른 국가의 MathWorks 사이트 방문이 최적화되지 않았습니다.
미주
- América Latina (Español)
- Canada (English)
- United States (English)
유럽
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom (English)
