How To Make Matplotlib Change Font
A practical step-by-step guide to how to make matplotlib change font, including preparation, instructions, common issues, tips, and next steps.
How To Make Matplotlib Change Font
Changing the default font in your Matplotlib plots is a simple way to improve their appearance, match your brand's style, or make your data visualisations clearer and more professional. The standard font can look a bit plain, but with a few lines of code, you can switch to any font available on your system. This guide will walk you through several methods, from making a quick change for a single plot to setting a new default font for all your future projects. We'll cover everything you need to know, including how to find available fonts and how to fix common problems that might pop up.
Fast Answer
- Global Font Change: Use plt.rcParams['font.family'] = 'Your Font Name'
- Specific Element: Use the fontdict argument in functions like plt.title()
- Troubleshooting: Rebuild the font cache if changes don't appear.
Before You Start
- A Python Environment: You'll need Python installed on your computer, along with the Matplotlib library. An environment like a Jupyter Notebook or a code editor such as VS Code is ideal.
- The Name of Your Desired Font: Know the exact name of the font you want to use (e.g., 'Arial', 'Times New Roman', 'Verdana'). We'll show you how to find a list of available fonts.
- (Optional) A Custom Font File: If you want to use a font that isn't installed on your system, you'll need its font file, usually ending in .ttf or .otf.
Step-by-Step Instructions
Step 1: Find Available Fonts on Your System
Before you can change the font, you need to know which fonts Matplotlib can actually see. The default font is often 'DejaVu Sans', which is fine but very common. To make your plots stand out, you'll want to choose something else. You can get a list of all the fonts Matplotlib recognizes on your computer.
To do this, you can run a short piece of Python code. This code imports the necessary part of Matplotlib called font_manager and then prints out a list of the font family names it finds.
import matplotlib.font_manager as fm
font_list = sorted([f.name for f in fm.fontManager.ttflist])
print(font_list)
Run this code. You will see a long list of font names printed out, such as 'Arial', 'Calibri', 'Courier New', and many others. Pick a font name from this list for the next steps. Make sure you copy the name exactly as it appears.
Step 2: Change the Font Globally with rcParams
The most common and powerful way to change the font is to set it for your entire script. This means every plot you create in that script will automatically use your chosen font for titles, labels, and ticks. This is done using Matplotlib's runtime configuration parameters, or rcParams for short.
Think of rcParams as a big dictionary of settings that control how your plots look. We're going to change the 'font.family' setting.
At the top of your Python script, right after you import Matplotlib, add the following lines. Replace 'Georgia' with the font name you chose in Step 1.
import matplotlib.pyplot as plt
plt.rcParams['font.family'] = 'Georgia'
Now, any plot you create will use the Georgia font. For example:
plt.figure()
plt.plot([0, 1], [0, 1])
plt.title('This is a Title in Georgia')
plt.xlabel('X-axis Label')
plt.ylabel('Y-axis Label')
plt.show()
When you run this, you should see that all the text on the plot has changed from the default to Georgia. This method is great for keeping a consistent style across a report or project.
Step 3: Change the Font for a Single Text Element
Sometimes, you don't want to change the font for the entire plot. You might want to make only the title stand out with a different font, size, or style. You can do this by passing a dictionary of font properties directly to the function that creates the text.
This is often done using the fontdict argument, which is available for functions like plt.title(), plt.xlabel(), and plt.ylabel(). Inside this dictionary, you can specify the font family, size, weight (like 'bold'), and style (like 'italic').
Here’s an example where we set the title to 'Times New Roman' and make it bold, while the rest of the plot uses the default font.
import matplotlib.pyplot as plt
title_font = {'family': 'Times New Roman', 'weight': 'bold', 'size': 16}
plt.figure()
plt.plot([0, 1], [0, 1])
plt.title('A Special Title', fontdict=title_font)
plt.xlabel('Default Font Label')
plt.show()
In this code, we first create a dictionary called title_font to hold our desired settings. Then, we pass it to plt.title() using fontdict=title_font. This gives you precise control over individual parts of your plot.
Step 4: Use Generic Font Families for Portability
What happens if you send your code to someone who doesn't have the 'Georgia' font installed? Matplotlib will show an error or fall back to its default font. To avoid this, you can use generic family names. These are 'serif' (like Times New Roman), 'sans-serif' (like Arial or Helvetica), and 'monospace' (like Courier).
When you set the font family to a generic name, Matplotlib will look for the best available font in that category on the current system. This makes your code more portable and less likely to break on different computers.
You can specify a list of fonts, starting with your most desired one and ending with a generic family as a fallback.
import matplotlib.pyplot as plt
plt.rcParams['font.family'] = 'sans-serif'
plt.rcParams['font.sans-serif'] = ['Verdana', 'Arial', 'DejaVu Sans']
In this example, we tell Matplotlib to use a sans-serif font. Then we give it a priority list: first, try to find and use 'Verdana'. If that's not available, try 'Arial'. If that also fails, use 'DejaVu Sans'. This is a very robust way to manage fonts.
Step 5: Use a Custom Font from a File
If you have a special font for your company or project that isn't installed on your system (for example, one you downloaded from Google Fonts), you can still use it. You just need to tell Matplotlib where to find the font file (usually a .ttf or .otf file).
You do this using the FontProperties object from the font manager. You create an instance of this object and pass the path to your font file. Then, you can use this object in the fontproperties argument of your text functions.
Let's say you have a font file named 'MyCustomFont.ttf' in the same folder as your script.
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
font_path = './MyCustomFont.ttf'
custom_font = FontProperties(fname=font_path)
plt.figure()
plt.plot([0, 1], [0, 1])
plt.title('Title in a Custom Font', fontproperties=custom_font, size=20)
plt.xlabel('X-axis in a Custom Font', fontproperties=custom_font, size=12)
plt.show()
This method is perfect for ensuring your visualisations have a unique and consistent brand identity, even if the font isn't widely available.
Step 6: Clear and Rebuild the Font Cache
This is the most important troubleshooting step for fonts in Matplotlib. As mentioned earlier, Matplotlib keeps a cache file of all the fonts it knows about to speed things up. If you install a new font on your system or add a custom font file, Matplotlib won't see it until this cache is updated.
If you've tried to use a new font and it's not working, or you get a "font not found" warning, you almost certainly need to rebuild the cache.
To do this, you need to run a simple piece of code. Important: After running this code, you must restart your Python session. If you're in a Jupyter Notebook, this means restarting the kernel. If you're running a script, just close the terminal and open a new one.
import matplotlib.font_manager
matplotlib.font_manager._rebuild()
After running this and restarting, Matplotlib will rescan your system for fonts, find the new one you installed, and your previous code should now work correctly. Do this anytime you make changes to the fonts on your computer.
Step 7: Make Permanent Font Changes with matplotlibrc
If you find yourself changing the font in every single script, you can make the change permanent by editing the Matplotlib configuration file, called matplotlibrc. This sets the default for your entire system, so you don't have to add the `rcParams` line to your code ever again.
First, you need to find where this file is located. You can find the path by running this code:
import matplotlib
print(matplotlib.matplotlib_fname())
This will print a file path. Navigate to that location on your computer and open the `matplotlibrc` file with a plain text editor (like Notepad or TextEdit). If the file doesn't exist, you can create it. Look for the line that starts with #font.family. The '#' symbol means the line is a comment and is currently ignored.
To set your new default font, remove the '#' at the beginning of the line and change the value. For example, to make 'Georgia' the default:
Change this:
#font.family: sans-serif
To this:
font.family: Georgia
Save the file. Now, every Matplotlib plot you create on your computer will use Georgia as the default font, without you needing to add any extra code. This is the ultimate "set it and forget it" solution.
Quick Reference
| Situation | Use this | Why |
|---|---|---|
| I want to change the font for everything in my current script. | plt.rcParams['font.family'] = 'Font Name' | Sets a consistent style for a single project or report. |
| I only want the plot's title to have a special font. | plt.title('My Title', fontdict={...}) | Gives you precise control over individual elements for emphasis. |
| My code needs to work on different computers. | plt.rcParams['font.family'] = 'sans-serif' | Uses a generic fallback to prevent errors if a specific font isn't installed. |
| I want to use a font I downloaded. | FontProperties(fname='path/to/font.ttf') | Allows for custom branding and use of non-system fonts. |
| My new font isn't showing up. | matplotlib.font_manager._rebuild() | Forces Matplotlib to rescan for fonts and fixes caching issues. |
| I want all my plots, forever, to use a new font. | Edit the matplotlibrc file. | Sets a permanent, system-wide default so you don't have to code it every time. |
Common Problems When You Change Matplotlib Font
Problem: I get a warning that the font was not found.
This is the most common issue. It usually means one of three things: you have a typo in the font name, the font is not installed on your system, or Matplotlib's cache is out of date. First, double-check the spelling of the font name against the list you generated in Step 1. If it's correct and the font is installed, then you need to rebuild the font cache as shown in Step 6 and restart your Python kernel.
Problem: Special characters (like math symbols or currency) look like squares.
This happens when the font you've chosen does not contain a glyph (a visual representation) for that specific character. Not all fonts support all characters, especially complex mathematical symbols, emojis, or characters from different languages. The solution is to either switch to a more comprehensive font (like 'DejaVu Sans', which has great character support) or to set a specific font for the math text using `rcParams`.
You can tell Matplotlib to use a specific font for math symbols like this:
plt.rcParams['mathtext.fontset'] = 'stix' # Or 'cm', 'dejavusans', etc.
Problem: The font looks different when I save the plot to a file (e.g., PDF or PNG).
Sometimes, the backend that Matplotlib uses to save files can handle fonts differently. For example, when saving to a PDF, fonts can be embedded into the file. If the font is not properly embedded, the PDF viewer might substitute it with a different font. To ensure consistency, make sure the font type is supported for embedding. TrueType fonts (.ttf) are generally the most reliable. You can also try saving in a different format, like SVG, which often handles text more flexibly.
Advanced Tips for Matplotlib Fonts
Using Style Sheets
For even more powerful and reusable styling, you can use Matplotlib's style sheets. These are like CSS for your plots. You can create a file (e.g., my_style.mplstyle) and define all your preferences in it, including the font family, size, and weight. Then, you just load this style at the beginning of your script with plt.style.use('./my_style.mplstyle'). This is fantastic for teams who need to produce plots with a consistent brand style.
Fonts in Different Environments
Be aware that fonts available on your local Windows or Mac machine may not be available in a cloud environment like Google Colab or a Docker container. When deploying code to a server, you will likely need to install the required font files on that server's operating system first, and then rebuild Matplotlib's font cache in that environment. Always plan for font installation as part of your deployment process.
Font Accessibility
When choosing a font, consider readability and accessibility. Sans-serif fonts like 'Arial' or 'Verdana' are often considered more readable for on-screen displays, especially for people with visual impairments or dyslexia. Ensure your font size is large enough and that there is sufficient contrast between the text colour and the background. Avoid overly decorative or stylistic fonts for important labels and data points.
How To Make Matplotlib Change Font FAQ
How do I change just the font size in Matplotlib?
You can change the font size globally using rcParams: plt.rcParams['font.size'] = 14. To change it for a specific element, use the 'size' key within a fontdict, like this: plt.title('My Title', fontdict={'size': 20}).
How can I make the font bold or italic?
This is also done with rcParams or a fontdict. For a global change, you would use plt.rcParams['font.weight'] = 'bold' or plt.rcParams['font.style'] = 'italic'. For a specific element, you would include it in the dictionary: plt.xlabel('X-axis', fontdict={'weight': 'bold', 'style': 'italic'}).
Can I use Google Fonts in Matplotlib?
Yes. First, download the font family from the Google Fonts website. You will get a ZIP file containing .ttf font files. Unzip it, and then you can use the method from Step 5 to point Matplotlib directly to the .ttf file path using FontProperties. Alternatively, you can install the font on your operating system and then rebuild the Matplotlib font cache.
Why does Matplotlib default to DejaVu Sans?
Matplotlib includes the DejaVu family of fonts as a default because they are open-source and have excellent coverage of a wide range of Unicode characters, including many scientific and mathematical symbols. This ensures that most plots will render correctly out of the box on any system, regardless of which fonts are installed locally. While it's not the most exciting font, it is very reliable.
Final Checklist for Changing Matplotlib Font
- Identify the Font: Use the font_manager to see a list of available fonts on your system and choose one.
- Choose Your Method: Decide if you want to change the font globally (rcParams), for a specific element (fontdict), or permanently (matplotlibrc).
- Apply the Change: Add the necessary line(s) of code to your script to set the new font family, size, or style.
- Rebuild Cache (If Needed): If you've installed a new font or your changes aren't applying, clear and rebuild the font cache.
- Restart Your Kernel: Always restart your Python session after rebuilding the cache for the changes to take effect.
- Verify the Output: Run your script and visually confirm that the font in your final plot has been updated as expected.