How to draw the axis in the origin of the coordinate system?
Mostrar comentarios más antiguos
Hello,
I want to make a figure that looks like this:

The code has always worked fine, but now it does not save the figure correctly anymore. (Maybe I updated MATLAB since last year, but I don't know; I am using R2025b and don't know, which one I used before.)
The exported figure looks like this:

The labels for f(x) and x are at the wrong places.
The error happens with exportfigure, print and manually saving the figure and png, jpg and pdf.
ChatGPT tells me, the problem is with "origin" but that there are only manual fixes which seem very complicated and unsatisfying to me.
Is there a fix for my figure / what should I do?
Thank you very much in advance!
%% Minimal Working Example
figureFontSize = 22;
set(0,'DefaultAxesFontSize',22)
lwidth=2;
xMin=-5;
xMax=+6;
xVal=(xMin:0.05:xMax);
% Aufgabe
yVal(:,1)=-2*(xVal-4).^2+64;
% Aufgabe
fig=figure(1);
plot(xVal,yVal(:,1),'-k','LineWidth',lwidth)
xlabel('x')
ylA=ylabel('f(x)');
xlim([xMin xMax])
a=max(abs(min(yVal(:,1))),max(yVal(:,1)));
ylim([-a-0.01*a +a])
set(gca, 'xtick', [])
set(gca, 'ytick', [])
ax = gca;
box('off')
grid('off')
set(gca, 'xticklabel', [])
set(gca, 'yticklabel', [])
ax.XAxisLocation = "origin";
ax.YAxisLocation = "origin";
% print(gcf,'test.png','-dpng','-r300')
exportgraphics(gcf,'test.png','Resolution',300)
Respuesta aceptada
Más respuestas (5)
You can try manually adding text descriptions at specified coordinates.
%% Minimal Working Example
figureFontSize = 22;
set(0,'DefaultAxesFontSize',22)
lwidth=2;
xMin=-5;
xMax=+6;
xVal=(xMin:0.05:xMax);
% Aufgabe
yVal(:,1)=-2*(xVal-4).^2+64;
% Aufgabe
fig=figure(1);
plot(xVal,yVal(:,1),'-k','LineWidth',lwidth)
% xlabel('x')
% ylA=ylabel('f(x)');
xlim([xMin xMax])
a=max(abs(min(yVal(:,1))),max(yVal(:,1)));
ylim([-a-0.01*a +a])
set(gca, 'xtick', [])
set(gca, 'ytick', [])
ax = gca;
box('off')
grid('off')
set(gca, 'xticklabel', [])
set(gca, 'yticklabel', [])
ax.XAxisLocation = "origin";
ax.YAxisLocation = "origin";
% manually add text descriptions at specified coordinates
text(xMax-0.5, -10, 'x', 'FontSize', 14)
text(0.5, 1.6*yVal(end,1), 'f(x)', 'FontSize', 14)
% print(gcf,'test.png','-dpng','-r300')
exportgraphics(gcf,'test.png','Resolution',300)
4 comentarios
Tina Fuhrmann
el 2 de Mzo. de 2026
Sam Chak
el 2 de Mzo. de 2026
It is likely that the function is broken in the latest version, and therefore, several workarounds have been suggested. I recommend filing a report with MathWorks to inform them of this bug.
Would it be possible to downgrade the software to the R2024b version since your code were working previously?

dpb
el 2 de Mzo. de 2026
"But I do not want to do this manually..."
Testing here shows it isn't just exporting; at the moment the drawn figure here is wrong, too.. Unfortunately, it appears that .R2025x is broken and can't be fixed internally except by Mathworks.
It looks like only thing that can do at the moment is something like
...
% Aufgabe
fig=figure(1);
plot(xVal,yVal(:,1),'-k','LineWidth',lwidth)
v=ver('MATLAB');
if fix(v.Version)>24
% inser the necessary label fixups here
...
....
else
% otherwise keep original code
xlabel('x')
ylA=ylabel('f(x)');
end
...
I though initially perhaps just swapping the x|ylabels would be sufficient, but while that does label the two axes as desired on which axes line the lables appear, the x label is then shown at the left and rotated 90 degrees because the internal axes are, in fact swapped internally.
While unpleasant, it would give you a version-independent routine until Mathworks can/does release a patch. At that time you could update the version test to limit it to cases that do include the bug.
Tina Fuhrmann
el 3 de Mzo. de 2026
Tweaking the properties of the xlabel and ylabel will put things the way you want them. (They are both text objects, so see that documentation for details.)
Try this --
%% Minimal Working Example
figureFontSize = 22;
set(0,'DefaultAxesFontSize',22)
lwidth=2;
xMin=-5;
xMax=+6;
xVal=(xMin:0.05:xMax);
% Aufgabe
yVal(:,1)=-2*(xVal-4).^2+64;
% Aufgabe
fig=figure(1);
plot(xVal,yVal(:,1),'-k','LineWidth',lwidth)
xlA = xlabel('f(x)');
ylA = ylabel('x');
ylA.Position(1) = max(xlim); % Change 'ylabel' X-Position
xlA.HorizontalAlignment = 'left'; % Change 'xlabel' 'HorizontalAlignment'
xlim([xMin xMax])
a=max(abs(min(yVal(:,1))),max(yVal(:,1)));
ylim([-a-0.01*a +a])
set(gca, 'xtick', [])
set(gca, 'ytick', [])
ax = gca;
box('off')
grid('off')
set(gca, 'xticklabel', [])
set(gca, 'yticklabel', [])
ax.XAxisLocation = "origin";
ax.YAxisLocation = "origin";
% print(gcf,'test.png','-dpng','-r300')
exportgraphics(gcf,'test.png','Resolution',300)
.
8 comentarios
Tina Fuhrmann
el 2 de Mzo. de 2026
My desktop computer just crashed, so I'm regenerating this on my laptop here.
It seems to work, although I had to increase the resolution to get the x-axis to show up.
I changed the xlabel and ylabel strings because that worked.
get_xla = get(xla)
get_yla = get(ylA)
Assigning them to variables is not necesssary, however it's easier to keep track of the results that way. They are structures, so you need to use structure 'dot referencing' to change their properties.
I wouldn't trust ChatGPT. It's not reliable.
My previous code, incluindig reading the saved figure (added here) --
%% Minimal Working Example
figureFontSize = 22;
set(0,'DefaultAxesFontSize',22)
lwidth=2;
xMin=-5;
xMax=+6;
xVal=(xMin:0.05:xMax);
% Aufgabe
yVal(:,1)=-2*(xVal-4).^2+64;
% Aufgabe
fig=figure(1);
plot(xVal,yVal(:,1),'-k','LineWidth',lwidth)
xlA = xlabel('f(x)');
ylA = ylabel('x');
ylA.Position(1) = max(xlim); % Change 'ylabel' X-Position
xlA.HorizontalAlignment = 'left'; % Change 'xlabel' 'HorizontalAlignment'
xlim([xMin xMax])
a=max(abs(min(yVal(:,1))),max(yVal(:,1)));
ylim([-a-0.01*a +a])
set(gca, 'xtick', [])
set(gca, 'ytick', [])
ax = gca;
box('off')
grid('off')
set(gca, 'xticklabel', [])
set(gca, 'yticklabel', [])
ax.XAxisLocation = "origin";
ax.YAxisLocation = "origin";
% print(gcf,'test.png','-dpng','-r300')
exportgraphics(gcf,'test.png','Resolution',500)
DemoPlot = imread('test.png'); % Read & Display The Saved Plot Image
figure
imshow(DemoPlot)
axis('padded')
.
Star Strider
el 3 de Mzo. de 2026
@Tina Fuhrmann -- I thought that my approach (using the text properties of the xlabel and ylabel objects) got you in the general vicinity of your 'workaround' code, since it seemed to produce the result you said you wanted.
What did I miss?
Tina Fuhrmann
el 3 de Mzo. de 2026
@Star Strider -- just taking a guess since @Tina Fuhrmann referred to everybody who had the workaround in one form or another, I expect choosing the specific version I posted was owing simply to having started from a clean slate and simplified the code to its barebones made it more convenient to pick up as just a couple of lines as it was formatted. A specific difference may also be that I set the 'VerticalPosition' properties and the "X" y-axis 'HorizontalPosition' to 'right' so it would be rendered inside the axis line itself as her original had it rather than past the end of the axis line.
One difference in appearance I noticed and am a little curious as to why the rendering appeared different is that without the extra spacing the same positioning using 'HorizontalPosition','left' drew the label closer to the x-axis line than I thought looked good; hence the extra offset. That still seems peculiar to me and not at all clear as to the cause of the visual difference.
A vote for all wouldn't be a bad "thank you!" ... <grins>
Tina Fuhrmann
el 3 de Mzo. de 2026
Star Strider
el 3 de Mzo. de 2026
I guess it doesn't really matter at this point.
The MWA is appropriate.
In my original Answer, I changed the strings in xlabel and ylabel and then used the text properties to change them to approximately produce what I assumed was the desired result. (With a few more properties changes, I could have used the original xlabel and ylabel strings. What I ended up doing just seemed easier.) Subsequently, I also read the written .png file to display how it had been saved, since that appeared to be the original problem.
Apparently it wasn't enough, or wasn't the desired solution.
Oh, well. Live and learn ...
You're ok, @Tina Fuhrmann. While the interface doesn't allow you to Accept more than one Answer, you can Vote for as many as you wish -- since most if not all had some positive direction towards solving the problem, I was just suggesting that a Vote for those would not be abadthing™ to acknowledge all the contributors.
I thought the simplest was simply to reposition the existing labels where they were wanted with their existing 'Position' properties; I didn't see any reason to muck with the text itself -- I didn't see @Star Strider's reponse initially so perhaps what he did there may explain the spacing difference observed.
I initially thought they had swapped the axes rather than only changed the default positions when I thought there was a real bug; I'm a little surprised they did allow as how it actually is one, but that is good that eventually it will get fixed -- the problem being that one can only try to keep up with what is already released into the wild.
Matt J
el 2 de Mzo. de 2026
1 voto
Use export_fig instead,
6 comentarios
Tina Fuhrmann
el 2 de Mzo. de 2026
Tina Fuhrmann
el 2 de Mzo. de 2026
dpb
el 2 de Mzo. de 2026
It appears the bug is that the x and y axes themselves are swapped.
Matt J
el 2 de Mzo. de 2026
Leads to the correct figure in MATLAB (again), but not in the png:
It does for me. Are you sure you're looking at the correct file?
Tina Fuhrmann
el 3 de Mzo. de 2026
Matt J
el 3 de Mzo. de 2026
It's a mystery to me. The output file I'm getting from your original code looks absolutely fine.
I can confirm the subject code works as expected to save the .png file without transposing axes labels in R2024b and R2021b
Submit this to Mathworks as a bug at <Product Support Page>
Unfortunately, there's probably nothing other than a fixup to be done in R2025b -- unless, what happens if you swap the x and y labels in the figure before exporting? It won't look right on the screen, but the exported one might then be correct depending upon just what is going wrong.
If the axes labels in the default positions aren't correctly rendered by default behavior, the function is broken.
2 comentarios
Tina Fuhrmann
el 2 de Mzo. de 2026
%% Minimal Working Example
xMin=-5;
xMax=+6;
xVal=(xMin:0.05:xMax);
% Aufgabe
yVal=-2*(xVal-4).^2+64; % don't need any subscripting here...
fig=figure(1);
set(fig,'DefaultAxesFontSize',22)
lwidth=2;
plot(xVal,yVal,'-k','LineWidth',lwidth)
hAx=gca;
xlabel('x')
ylA=ylabel('f(x)');
xlim([xMin xMax])
a=max(abs(yVal));
ylim([-a-0.01*a +a])
yticks([]); xticks([])
box off; grid off
hF=figure;
set(hF,'DefaultAxesFontSize',22)
hAx(2)=copyobj(hAx,hF);
hAx(2).XAxisLocation = 'origin';
hAx(2).YAxisLocation = 'origin';
I was mistaken before; the axes aren't interchanged; only that with R2025 it appears that Mathworks has made the X axis label appear at the origin of the X-axis in the x-direction and at the top (maximum) and the Y-axis instead of at the maximum of the x-axis and at the location of the y. And vice versa with the y-label that was at the origin in the x direction and at the maximum in the y-direction. These locations make sense from that standpoint even though the eye may (as I did) first misinterpret them more easily I think.
Mathworks isn't going to think this is a bug; they might accept a request for an option to have a way to get the prior behavior.
Let's see...
hF=figure;
set(hF,'DefaultAxesFontSize',22)
hAx(3)=copyobj(hAx(2),hF);
hAx(3).XAxisLocation = 'origin';
hAx(3).YAxisLocation = 'origin';
hLX=hAx(3).XAxis.Label;
hLX.Position=[xMax,0]; hLX.HorizontalAlignment='right'; hLX.VerticalAlignment='bottom';
hLY=hAx(3).YAxis.Label;
yl=ylim; yMax=yl(2); % upper y limit
hLY.Position=[0,yMax]; hLY.HorizontalAlignment='left'; hLY.VerticalAlignment='top';
isn't too bad -- might want to add just a little offset to the x-axis position in the +x direction.
%% Minimal Working Example
xMin=-5;
xMax=+6;
xVal=(xMin:0.05:xMax);
% Aufgabe
yVal=-2*(xVal-4).^2+64; % don't need any subscripting here...
hF=figure;
set(hF,'DefaultAxesFontSize',22) % set for the specific figure only, not root
lwidth=2;
plot(xVal,yVal,'-k','LineWidth',lwidth)
hAx=gca;
hLx=xlabel('x'); % save handle to x label
hLy=ylabel('f(x)'); % and y, too....
xlim([xMin xMax])
a=max(abs(yVal)); % max(abs(x)) is all needed here
ylim(a*[-1.01 1.00]) % slightly cleaner range calculation
yticks([]); xticks([]) % shorter syntax to not show ticks (labels go away then, too)
box off; grid off
hAx.XAxisLocation = 'origin';
hAx.YAxisLocation = 'origin';
hLx.Position=[xMax,0]; hLx.HorizontalAlignment='right'; hLx.VerticalAlignment='top';
yl=ylim; yMax=yl(2); % upper y limit
hLy.Position=[0+xMax/25,yMax]; hLy.HorizontalAlignment='left'; hLy.VerticalAlignment='top';
isn't too bad...probably need to figure out a more generic offset in the y-label x position to handle varying x ranges.
The code to reposition the two labels would be the code to put in the suggested version-specific code section if would need to run this in various versions. The alternative would be a test on where the positions of the two labels are.
As noted above, I was in error in thinking it an actual bug but I still think an option to revert to prior behavior would be welcome.
3 comentarios
Tina Fuhrmann
el 3 de Mzo. de 2026
@Tina Fuhrmann -- I also think the more recent penchant of Mathworks to make unilateral changes breaking backwards compatibility is a real issue for users and can be extremely costly to them in wasted manhours futzing with such things as this. I've complained (whined?) for 30 years about when still in the consulting gig that it would take far more time to clean up graphics to be presentable to clients than it did to do the field work and analyses to begin with. In those days, there really was no other all-inclusive option that combined all the needed math/stat libraries with graphics when the alternative was a FORTRAN compiler and the IMSL libraries or an independent downloading of LINPACK, etc., and then a set of graphics primitives to compile and link or to do all the graphics in some other standalone product such as TecPlot (although that had some real advantages in the scope and quality of the produced graphics and still does for many cases).
On the syntax, I figured there probably was such a reason but pointed out "just in case" was some inherited code and didn't recognize it.
As for the difference between using set and the builtin xticks, functionally they're the same, yes; the difference is simply one of brevity in the user code; behind the scenes unless one has already saved and uses the two argument form to pass the explicit axes handle, the gca call will be there anyway. It is more efficient and safer code to save the axes handle on creation and then use it to ensure are always addressing the desired axes although for a single user and linear code a context switch isn't too likely, in an app, focus can be changed behind your back. And, explicitly calling gca every time is another functional call that could be saved for just a minor efficiency improvement.
Example with the idea of adding blank in front of ylabel instead of a computed offset to move away from the x-axis line a little...
%% Minimal Working Example
xMin=-5;
xMax=+6;
xVal=(xMin:0.05:xMax);
% Aufgabe
yVal=-2*(xVal-4).^2+64; % don't need any subscripting here...
hF=figure;
set(hF,'DefaultAxesFontSize',22) % set for the specific figure only, not root
lwidth=2;
plot(xVal,yVal,'-k','LineWidth',lwidth)
hAx=gca;
hLx=xlabel('x'); % save handle to x label
hLy=ylabel('f(x)'); % and y, too....
xlim([xMin xMax])
a=max(abs(yVal)); % max(abs(x)) is all needed here
ylim(a*[-1.01 1.00]) % slightly cleaner range calculation
yticks([]); xticks([]) % shorter syntax to not show ticks (labels go away then, too)
box off; grid off
hAx.XAxisLocation = 'origin';
hAx.YAxisLocation = 'origin';
hLx.Position=[xMax,0]; hLx.HorizontalAlignment='right'; hLx.VerticalAlignment='top';
yl=ylim; yMax=yl(2); % upper y limit
hLy.Position=[0,yMax]; hLy.HorizontalAlignment='left'; hLy.VerticalAlignment='top';
hLy.String=append(blanks(1),hLy.String); % add a blank to adjust x position a tad to right...
That is improved and not dependent upon the scaling of the axes...of course, still be better to not have to make the fixup at all when gets fixed.
Categorías
Más información sobre Graphics Object Programming en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!













