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 fonts in Matplotlib allows you to customise your plots for better readability, a specific brand look, or just to make them more interesting. This guide will walk you through the process, from picking a standard font to adding your own custom styles. You'll learn how to update all your plot fonts at once or tweak individual parts like titles and labels, ensuring your data visualisations always look their best and communicate clearly.
Fast Answer
- Set global font: `plt.rcParams['font.family'] = 'Font Name'`
- Set global font size: `plt.rcParams['font.size'] = 12`
- Update plot element: `plt.xlabel('X-axis', fontsize=14, fontfamily='Font Name')`
Before You Start
- Python installed: Ensure you have Python 3.x installed on your computer. You can download it from the official Python website.
- Matplotlib installed: You'll need the Matplotlib library. If you don't have it, open your terminal or command prompt and run `pip install matplotlib`.
- Basic Python knowledge: Understand how to open a Python script, run basic commands, and create a simple plot using Matplotlib.
- Text editor or IDE: Use a tool like VS Code, PyCharm, or even a simple text editor to write and save your Python code.
- Access to command line/terminal: Needed for installing libraries and clearing font caches if you use custom fonts.
Step-by-Step Instructions
Step 1: Get Ready and Create a Basic Plot
Before you start changing fonts, let's set up your Python environment and create a very simple plot. This will give you something to test your font changes on. Open your text editor or IDE and create a new Python file, for example, `font_test.py`.
Start by importing Matplotlib and NumPy (which is often used with Matplotlib for creating data easily). Then, make a simple line plot.
Run this script. You should see a plot with the default Matplotlib font. This is your starting point. Close the plot window to continue.
Step 2: Change the Font for All Parts of Your Plot (Globally)
The easiest way to change the font for everything in your Matplotlib plots is to use `rcParams`. This stands for "runtime configuration parameters" and lets you set default values for many Matplotlib settings, including fonts. You'll typically set these at the very beginning of your script, after your imports.
Let's change the default font family and size for all elements in your plot. You need to know the exact name of a font installed on your system. Common choices include 'Arial', 'Verdana', 'Times New Roman', 'Courier New', or generic families like 'serif', 'sans-serif', 'monospace'.
Add these lines *after* `import matplotlib.pyplot as plt` and *before* your plot creation code:
Run the script again. You should see that the title, labels, and tick numbers are all now in 'Times New Roman' (or whichever font you chose) and a size of 14 points. If Matplotlib can't find 'Times New Roman', it will use a different default font, so make sure the spelling is exact and the font is installed on your operating system.
Step 3: Adjust Font Weight and Style Globally
Besides changing the font family and size, you can also adjust the font weight (like bold or normal) and style (like italic). These are also set using `rcParams` and apply to all text elements in your plot.
Let's make the text bold and slightly more spaced out using a different font. Add or modify these lines in your global font settings:
Run the script. All text in the plot should now appear in bold 'Verdana' font. Experiment with `'normal'`, `'bold'`, `'heavy'`, `'light'`, `'ultralight'` for `font.weight` and `'normal'`, `'italic'`, `'oblique'` for `font.style` to see the differences.
Step 4: Change Font for Specific Plot Elements
Sometimes you only want to change the font for a particular part of your plot, like just the title or just the x-axis label, while leaving everything else as the default or another setting. Matplotlib allows you to do this by passing font arguments directly to the functions that create those elements.
Let's keep the global font as 'Verdana' (from Step 3) but make the title 'Times New Roman' and a bit larger, and the x-axis label italic.
Notice how the `plt.title()` and `plt.xlabel()` functions now have `fontsize`, `fontfamily`, `fontweight`, and `fontstyle` arguments. These specific settings override the global `rcParams` for just that element. The y-axis label still uses the global 'Verdana' font and size 12 because we didn't specify otherwise.
Step 5: Using Custom Fonts (More Advanced)
If you have a special font file (like a `.ttf` or `.otf` file) that isn't installed on your system or Matplotlib isn't finding it, you can tell Matplotlib where to look for it. This is a bit more involved because Matplotlib keeps a cache of fonts it knows about.
First, you need to make sure your custom font file is accessible. For this example, let's assume you have a font file named `MyCustomFont.ttf` in the same folder as your Python script.
To make this work reliably, sometimes Matplotlib's font cache needs to be rebuilt. If your custom font doesn't appear after running the script, you might need to manually clear Matplotlib's font cache. You can do this by deleting the cache file. The location varies by operating system:
- Windows: Look in `C:\Users\\.matplotlib` for a file named something like `fontlist-*.json` or `fontlist-*.cache`.
- macOS/Linux: Look in `~/.matplotlib` for a file named something like `fontlist-*.json` or `fontlist-*.cache`.
Delete that file, then restart your Python environment and run the script again. Matplotlib will rebuild its cache, including your custom font. Using custom fonts can be tricky, so patience and checking file paths are key!
Step 6: Resetting Matplotlib Font Settings
After experimenting with various font settings, you might want to revert Matplotlib back to its original default appearance. This is straightforward using the `plt.rcdefaults()` function.
Add `plt.rcdefaults()` at any point in your script where you want to undo previous `rcParams` changes. Typically, you'd do this to start fresh for a new set of plots, or at the very beginning of a script if you want to ensure no previous settings from a configuration file interfere.
When you run this script, you'll first see a plot with 'Times New Roman' bold text. After you close that window, the settings are reset, and the second plot will appear with Matplotlib's original default font and size. This function is very useful for ensuring consistency or for debugging.
Quick Reference
| Situation | Use this | Why |
|---|---|---|
| Change font for all plot elements | plt.rcParams['font.family'] = 'Arial' plt.rcParams['font.size'] = 14 |
Sets a consistent look across titles, labels, and ticks for all plots created afterward. |
| Change font for just the plot title | plt.title("My Title", fontsize=16, fontfamily='Georgia', fontweight='bold') | Overrides global settings for the title only, allowing specific styling for emphasis. |
| Change font for an axis label | plt.xlabel("X Data", fontsize=12, fontstyle='italic') | Applies specific font size and style to a single axis label without affecting others. |
| Use a custom font from a file | import matplotlib.font_manager as fm font_path = './MyCustomFont.ttf' fm.fontManager.addfont(font_path) prop = fm.FontProperties(fname=font_path) plt.rcParams['font.sans-serif'] = [prop.get_name()] + plt.rcParams['font.sans-serif'] |
Allows Matplotlib to use fonts that aren't globally installed on your system or are not found by default. Requires cache clearing if issues occur. |
| Reset all font settings to default | plt.rcdefaults() | Clears all `rcParams` changes, including font settings, bringing Matplotlib back to its original state. Useful for starting fresh. |
Common Problems When You Make Matplotlib Change Font
Problem: Font Not Changing or Showing a Generic Font
Reason: This is the most common issue. It usually means Matplotlib couldn't find the font you specified. This could be due to a typo in the font name, the font not being installed on your operating system, or Matplotlib's font cache not being updated.
Solution:
- Check Font Name: Double-check the spelling of the font name in your code. Font names are case-sensitive on some systems.
- Verify Installation: Ensure the font is actually installed on your computer. On Windows, check "Fonts" in Control Panel. On macOS, use "Font Book". For custom fonts, make sure the `.ttf` or `.otf` file is in the correct directory and accessible.
- Clear Matplotlib Cache: If you've recently installed a new font or added a custom font, Matplotlib might not "see" it yet. Delete the font cache file (e.g., `fontlist-*.json` or `fontlist-*.cache`) from your Matplotlib configuration directory (`~/.matplotlib` on Linux/macOS, `C:\Users\\.matplotlib` on Windows). Then, restart your Python script.
- Use Generic Families: As a fallback, use generic font families like `'serif'`, `'sans-serif'`, or `'monospace'`. Matplotlib will then pick the best available font from that category.
Problem: Custom Font Not Loading Even After Clearing Cache
Reason: While clearing the cache often helps, sometimes Matplotlib struggles with specific font files or their permissions, or the way it's referenced.
Solution:
- Check File Path: Ensure the `font_path` in your code (from Step 5) is absolutely correct and uses forward slashes (`/`) even on Windows for consistency.
- Permissions: Make sure the Python script has permission to read the font file. If the font file is in a restricted folder, Matplotlib might not be able to access it.
- Font File Integrity: Some font files can be corrupted or in a format Matplotlib doesn't fully support. Try a different font file if possible.
- System-Wide Installation: As a last resort, consider installing the custom font directly onto your operating system if it's meant for general use. This often makes it easier for Matplotlib to find it.
Problem: Font Size or Weight Not Applying Correctly
Reason: This usually comes down to conflicts between global `rcParams` and specific settings applied to individual plot elements, or incorrect values for `font.weight` or `font.style`.
Solution:
- Check Overrides: Remember that direct arguments to functions like `plt.title()` (`fontsize=16`) will override global `rcParams` for that specific element. If you set a global size to 14, but then `plt.title(fontsize=18)`, the title will be 18.
- Valid Values: Ensure you are using valid strings for `font.weight` (e.g., `'normal'`, `'bold'`, `'light'`, `'heavy'`) and `font.style` (e.g., `'normal'`, `'italic'`, `'oblique'`). Invalid values might be ignored.
- Order of Operations: If you set `rcParams` *after* creating an element, that element won't reflect the new `rcParams`. Set global `rcParams` at the start of your script.
Advanced Tips for How To Make Matplotlib Change Font
- Using `matplotlibrc` for Permanent Changes:
Instead of setting `rcParams` in every script, you can create a special configuration file called `matplotlibrc`. Matplotlib automatically loads settings from this file. This is great for consistent styling across all your projects without repeating code.
To find where Matplotlib expects this file, run `matplotlib.matplotlib_fname()` in Python. Then, create a text file named `matplotlibrc` in that directory (or a directory specified in your `MPLCONFIGDIR` environment variable) and add your desired font settings:
This will set these as default for all your Matplotlib plots. Remember to restart your Python environment after creating or changing this file.
- Specifying Fallback Fonts:
When you set `font.family` to a generic name like `'sans-serif'` or `'serif'`, Matplotlib uses a list of specific fonts. You can control this list by setting `font.sans-serif` or `font.serif` in `rcParams`.
Matplotlib will try 'Helvetica Neue' first. If it's not available, it moves to 'Arial', then 'Liberation Sans', and so on. This makes your plots more robust across different systems.
- Using Text Properties for Fine Control:
For even more advanced control over text elements, Matplotlib provides a `Text` object. You can get and set properties on these objects directly. This is useful when you want to modify existing text elements dynamically.
- LaTeX Integration for Scientific Plots:
If you're creating scientific or mathematical plots, Matplotlib can use LaTeX to render all text, allowing you to use high-quality typesetting and include complex mathematical symbols with the exact fonts you define in LaTeX. This requires a LaTeX distribution (like TeX Live or MiKTeX) to be installed on your system.
Using LaTeX offers the highest quality text rendering but adds a dependency and can be slower. The `r` before the string (e.g., `r'\textbf{...'`) ensures Python treats it as a raw string, which is important for LaTeX commands.
How To Make Matplotlib Change Font FAQ
Why should I change fonts in Matplotlib?
What's the difference between 'serif' and 'sans-serif'?
How do I find out what fonts are available on my system?
- Windows: Go to 'Control Panel' > 'Appearance and Personalization' > 'Fonts'.
- macOS: Open the 'Font Book' application (found in Applications/Utilities).
- Linux: Fonts are typically in `/usr/share/fonts/` or `~/.fonts/`. You can also use font management tools specific to your desktop environment.
Can I use different fonts for different text elements in the same plot?
Why is my custom font not showing up even after I add it?
Final Checklist for How To Make Matplotlib Change Font
- Global Font Settings Applied? Have you set `plt.rcParams['font.family']` and `plt.rcParams['font.size']` at the beginning of your script if you want a consistent look?
- Specific Elements Styled? Have you used `fontsize`, `fontfamily`, `fontweight`, or `fontstyle` arguments directly in `plt.title()`, `plt.xlabel()`, etc., for fine-grained control?
- Font Names Correct? Is the spelling of your chosen font families exact and case-sensitive (where applicable)?
- Custom Fonts Handled? If using custom fonts, have you added them with `fm.fontManager.addfont()` and updated `rcParams` to include them?
- Cache Cleared if Needed? For new or custom fonts, have you deleted Matplotlib's font cache file and restarted your Python environment if the changes aren't appearing?
- Readability Checked? Does your chosen font and size combination make the plot clear and easy to read, or is it too small/large or difficult to distinguish?
- Plot Saved with New Fonts? When saving your plot (`plt.savefig()`), does the output file (e.g., PNG, PDF) correctly display the updated fonts?
- Default Settings Reset if Desired? If you want to revert to Matplotlib's original defaults for subsequent plots, have you used `plt.rcdefaults()`?