How do I change the font size for text in my figure?

조회 수: 2,586 (최근 30일)
Edward
Edward 2014년 5월 26일
이동: Adam Danz 2024년 5월 13일
I'm using "set(gca,'fontsize', 18);" in a function to change fonts in a figure. My code does not throw an error, but it also does not change the font size. I can manually change the fonts via the UI, but this is a slow process. I'm running MATLAB 2013a on RHEL6.5
I've also tried "set(gca,'FontSize', 18);" and specifying 'FontSize', 18 in title, xlabel, ylabel and legend. None of these have worked.
Please advise!
  댓글 수: 14
Adam Danz
Adam Danz 2022년 11월 23일
이동: Adam Danz 2024년 5월 13일
S = settings();
S.matlab.fonts.codefont.Size.TemporaryValue = 14; % fontsize (points)
This will persist until you close MATLAB so you could put this in your startup function if you want this to take affect every time you open MATLAB.
Revert to default using
clearTemporaryValue(S.matlab.fonts.codefont.Size)
Piotr
Piotr 2024년 5월 13일
이동: Adam Danz 2024년 5월 13일
Very useful, thanks

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

채택된 답변

Adam Danz
Adam Danz 2022년 3월 18일
편집: Adam Danz 2023년 4월 18일
Here is a review of several solutions shared across 9 years in this thread and some guidance on deciding how to control font size in your graphics.
Starting in MATLAB R2022a
Use the fontsize function to set font sizes and font units in a figure.
Set a single font size and specify font units for text objects in a figure/axes/object using
fig = figure();
fontsize(fig, 24, "points")
Incrementally increase or decrease font size of text objects while maintaining relative differences in font size using
fontsize(fig, "increase")
fontsize(fig, "decrease")
fontsize(fig, scale=1.2) % 120%
See the fontsize page for more options and information.
Release R2022a also includes the fontname function to set font names within a figure.
For a review and examples, see this Community Highlight.
Alternatives to controlling FontSize prior to R2022a
The font size of text objects can be directly set from within text convenience functions:
title('My title', 'FontSize', 24)
xlabel('x axis', 'FontSize', 24)
ylabel('y axis', 'FontSize', 24)
text(0.5, 0.5, 'My label', 'FontSize', 24)
Or, you can set the font size of the text object after it is created:
th = title('My title');
th.FontSize = 24;
The font size of axes components can be set from within the axes' FontSize property. This will not affect text objects that do not belong to the axes:
plot(rand(5))
xlabel('x axis')
ylabel('yaxis')
title('My title')
text(3, .5, 'this') % will not be affected
ax = gca;
ax.FontSize = 16;
Another option is to find all objects in a figure with a FontSize property and to set the font size in those objects.
set(findall(gcf,'-property','FontSize'),'FontSize',24)
Common issues
Issue 1: After creating an axes and adding a text object to the axes with a specified font size, the specified font size is lost. Here's an example:
clf
ax = axes('FontSize', 24);
plot(rand(5))
ax.FontSize
ans =
10
The reason this happens is because some properties of new axes are reset after adding objects to the axes. This can be prevented in a couple of ways.
Solution 1: Retain axes properties by calling hold on after setting the axes font size.
clf
ax = axes('FontSize', 24);
hold on
plot(rand(5))
Solution 2: Set the axes font size after plotting
clf
plot(rand(5))
ax = axes('FontSize', 24);
Issue 2: If you specify font size using TeX markup, that object will not respond to font size change commands.
ax = axes();
xlabel('x axis')
ylabel('y axis')
th = title('\fontsize{24} My title');
th.FontSize = 8; % does not affect the title
The solution is to choose between specifying font size as TeX markup or by using the font size property.

추가 답변 (11개)

Mike Garrity
Mike Garrity 2016년 2월 10일
Yes, this can be confusing. Here's what you're probably seeing:
figure % Creates a figure
set(gca,'FontSize',18) % Creates an axes and sets its FontSize to 18
plot(x,y) % Resets the axes and plots into it
Notice the "Resets the axes" part. One of the things that happens there is that the FontSize property gets set to the default!
This doesn't happen when hold is on because then the axes doesn't get reset.
There are a couple of ways around this.
The simplest is to set the FontSize after plotting.
A somewhat more complicated way is to change the default:
figure('DefaultAxesFontSize',18)
plot(x,y)
Does that make sense?
  댓글 수: 1
Rik
Rik 2017년 2월 9일
The point is that the font size property is inherited from the figure. So instead of calling gca, you should call gcf. But indeed, best practice is setting the font size on creation of the figure window.

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


José Crespo Barrios
José Crespo Barrios 2016년 2월 10일
set(findall(gcf,'-property','FontSize'),'FontSize',18)
  댓글 수: 5
Mauricio Iwanaga
Mauricio Iwanaga 2021년 4월 15일
Many thanks. It worked perfectly fine to my case. Apparently, change fontsize in Matlab text function is not so trivial, but your tip works really good (I'm using Matlab R2021a).
Image Analyst
Image Analyst 2021년 4월 16일
@Mauricio Iwanaga I'm not sure of your definition of "trivial", but the text() function also has a 'FontSize' option:
text(x, y, str, 'FontSize', 18, 'FontWeight', 'bold');
It seems pretty trivial to me to use it, once you know that that input option is available.

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


Image Analyst
Image Analyst 2014년 5월 27일
Usually you can set the font size on every control individually as you update its text, like
title('This is my plot', 'FontSize', 24);
xlabel('x axis', 'FontSize', 24);
text(x, y, 'Hey, look at this', 'FontSize', 24);
What's wrong with doing it like that? That's what I do.
  댓글 수: 5
Image Analyst
Image Analyst 2014년 5월 29일
I don't know. That's bizarre. You should call tech support.
Peter
Peter 2016년 9월 27일
well, probably this font is not available in other sizes

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


Sean de Wolski
Sean de Wolski 2014년 5월 27일
I think what you want to do is set the 'Default' font size for the axes
set(gca,'DefaultTextFontSize',18)
Now any text object on that axes will have 18 font
text(0.5,0.5,'hello')
  댓글 수: 4
Image Analyst
Image Analyst 2020년 2월 11일
Or, since r2014b, you can do it without the set() function:
ax = gca;
ax.DefaultTextFontSize = 18;
DN7
DN7 2020년 12월 18일
If gca does not work for you, make sure you didn't accidentally create a variable named that way. use:
clearvars gca
h_gca=gca;
h_gca.FontSize=13;
to ensure that. I accidentally created this variable (struct) when I ran gca.FontSize = 13, which does not change the font size of the current axis, but instead creates a new struct.

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


Daniel
Daniel 2015년 3월 26일
I just wanted to weigh in on this given I've spent the last couple of hours looking into this.
I am running Matlab 2013b on Ubuntu 12.04LTS. Similar as many here, changing labels/legend properties works fine but setting the axis ticklabel fontname/size was not working - at least, the axis property list reflected the change, but the window plot was not rendering to the new font settings. After printing the plot to eps and including this in my latex compiled document, it turns out the axis font properties were changing. It would appear to be just a rendering bug.
Installing additional fonts did not work for me - and I did not expect to, since rendering/changing font properties of other objects such as labels and legends worked fine in Matlab.
So for those of you cocnerned with the looks of your plots for publications, it would appear to me that the actual exported figures do reflect the editing (at least this was my experience when printing to .eps).
Cheers,
Daniel

Renato Campana
Renato Campana 2017년 11월 18일
Im working with Matlab 2016. You can tried two things:
1)figure('DefaultAxesFontSize',30); % here the font size is 30. figure (1) plot(x,y,'LineWidth',4); % note that the linewidth here is 4 xlabel('length bar','FontSize',18); % note that the font size label here is 18 ylabel('wide bar','FontSize',18); % note that the font size label here is 18
and you must to use the dame command figure('DefaultAxesFontSize',30) in each figure. If you dont specified the font size in each label, the labels shows the size in "30"
Or you can tried:
2) figure (1) plot(x,y,'LineWidth',4); set(gca,'FontSize',28); % please, note that the font size is AFTER the plot command :)

Anu
Anu 2015년 1월 1일
I have also encountered the same problem. I was using Linux Mint OS. I solved it by installing the xfont 100 and 75 dpi and the truetype fonts. Try it out once.

Image Analyst
Image Analyst 2020년 5월 10일
이동: Image Analyst 2023년 4월 18일
Here is code that shows you how to change just about anything about the axes that you want:
% Demo to make a black graph with blue title, red Y axis, green X axis, and yellow grid.
% Initialization steps:
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
clearvars;
workspace; % Make sure the workspace panel is showing.
format long g;
format compact;
fontSize = 24;
% Create sample data.
X = 1 : 20;
Y = rand(1, 20);
plot(X, Y, 'gs-', 'LineWidth', 2, 'MarkerSize', 10);
grid on;
title('Y vs. X, Font Size 12', 'FontSize', 12, 'Color', 'b', 'FontWeight', 'bold');
% Make labels for the two axes.
xlabel('X Axis, Font Size 15');
ylabel('Y axis, Font Size 24');
yticks(0 : 0.2 : 1);
% Get handle to current axes.
ax = gca
% This sets background color to black.
ax.Color = 'k'
ax.YColor = 'r';
% Make the x axis dark green.
darkGreen = [0, 0.6, 0];
ax.XColor = darkGreen;
% Make the grid color yellow.
ax.GridColor = 'y';
ax.GridAlpha = 0.9; % Set's transparency of the grid.
% Set x and y font sizes.
ax.XAxis.FontSize = 15;
ax.YAxis.FontSize = 24;
% The below would set everything: title, x axis, y axis, and tick mark label font sizes.
% ax.FontSize = 34;
% Bold all labels.
ax.FontWeight = 'bold';
hold off

vimal kumar chawda
vimal kumar chawda 2020년 8월 12일
figure(4)
set(gca,'FontSize',50)
plot(A_OBS(2).RxTime(:)/3600, No_ele2(1:r2, 1), '.b');
hold on;
plot(A_OBS(4).RxTime(:)/3600, No_ele4(1:r4, 1)-0.05, '.g');
xlabel('Time [h], Font size 15');
ylabel('Number of visible satellites,Font size 15');
title('Comparison between Javad and u-blox receivers (Gallileo)');
legend('Javad(SN:0082)','u-blox(SN:1771)');
Why it is not working ?
I need to maximize the scale and the text in the axis scale.
  댓글 수: 2
Elias Salilih
Elias Salilih 2023년 8월 4일
I understood that font size of axis numbers can be changed with "set(gca,'FontSize',50)", how about font size of a double axis plot (I mean plotyy)
DGM
DGM 2023년 8월 4일
The plotyy() function creates two axes objects. You can set their properties separately.
x = 0:0.01:20;
y1 = 200*exp(-0.05*x).*sin(x);
y2 = 0.8*exp(-0.5*x).*sin(10*x);
hp = plotyy(x,y1,x,y2); % get axes handles
% set properties of each axes
% i'm going to use different sizes for sake of clarity
hp(1).FontSize = 8; % controls xruler and LH yruler
hp(2).FontSize = 16; % controls RH yruler

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


Eitvydas Karauskas
Eitvydas Karauskas 2021년 4월 4일
Hey guys, I have a different problem with text function. Why does my text size changes when I zoom in or out of my graph? I need to put text at a fixed sized, so it doesn't change when I zoom in or out. I'm adding my code.
Thanks for help ;)
%defining latitude and longitude
latlim=[53.9 55.5];
lonlim=[24 26];
%loading world map
map=worldmap(latlim,lonlim);
%loading lithuania borders from external source and displaying it as a
%geografic coordinates
country=shaperead('gadm36_LTU_0.shp','usegeocoords',true,'BoundingBox', [lonlim', latlim']);
geoshow(map,country,'facecolor',[1 1 1],'linewidth',2);
%converting coordinates to lat/lon
%defining VNO
VNOlon = 25.293639;
VNOlat = 54.636056;
geoshow( VNOlat, VNOlon, 'marker','.', 'markerfacecolor','blue','markeredgecolor','blue','markersize',6);
textm(VNOlat,VNOlon, 'VNO','fontweight','bold','color','black','fontsize',6);
%converting km to nn and defining radius
r = [ 9.26 18.52 27.78];
circlem(VNOlat,VNOlon,r,'linestyle','--','linewidth',0.5);
%defining radius from VNO
textm(54.65831449445, 25.14947845266, '5nm VNO','rotation',70,'fontsize',3,'fontunits','normalized');

Michael Neely
Michael Neely 2021년 11월 20일
None of the above answers on using a single line to "set gca" or "set default" actually work. I have had success setting the fonts in individual print commands (as some of the answers suggest). However, it is quite annoying that there is no simple way to put one line that changes the font size for everything.
The only way I can do it is to physically operate on the figure itself, clicking and enlarging, and this seems to be highly dependent on the size of my window that I use to display the figure. If I physically enlarge the window then the fonts might be modified. This makes it very difficult to consistently print figures for a publication. Some figures will have font sizes slightly different than others.
  댓글 수: 2
Romanos Sahas
Romanos Sahas 2022년 10월 3일
편집: Romanos Sahas 2022년 10월 3일
Assuming that you have used 'text(...)' while creating your figure and it is the resulting labels that you want to target, here is a fix which worked for me.
g = gcf;
set(findall(g,'Type','text'),'FontSize',14)
Adam Danz
Adam Danz 2022년 10월 3일
@Romanos Sahas, starting in MATLAB R2022a, you could use the fontsize function to do exactly that:
fontsize(gcf, 14, 'points')
For a review, see this Community Highlight.

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

카테고리

Help CenterFile Exchange에서 2-D and 3-D Plots에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by