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
Matplotlib is a powerful tool for creating graphs and charts in Python. Changing the font in your Matplotlib plots can make them look much better and easier to read. This guide will show you how to update font styles, sizes, and families for all text in your plots or for specific parts like titles and labels. Following these steps helps ensure your data visualizations are professional and visually appealing for reports, presentations, or web content.
Fast Answer
- Global Font Family: `matplotlib.rcParams['font.family'] = 'serif'`
- Global Sans-serif Font: `matplotlib.rcParams['font.sans-serif'] = ['Arial', 'Helvetica']`
- Specific Text Element Font: Use `fontname='Your Font'` in plot function calls
Before You Start
- Python installed: Ensure you have Python 3.x installed on your computer.
- Matplotlib installed: You need Matplotlib, usually installed via `pip install matplotlib`.
- A code editor: Any basic text editor or an integrated development environment (IDE) like VS Code, PyCharm, or Jupyter Notebook will work.
- Basic Python knowledge: Understanding how to run Python scripts and import libraries is helpful.
Step-by-Step Instructions
Step 1: Get Your Matplotlib Project Ready
Before you can change any fonts, you need to open your Python environment and import the Matplotlib library. This is the first step for any project that uses Matplotlib to create plots.
Start by creating a new Python file or opening your existing script. At the very top, add the necessary import statements.
import matplotlib.pyplot as plt import numpy as npThis line is important for font management, especially if you add new fonts
from matplotlib import font_manager
Step 2: Check Which Fonts Are Available on Your System
It's a good idea to know which fonts Matplotlib can currently access. This helps prevent errors if you try to use a font that isn't installed or registered with Matplotlib's font system. You can list all the font families Matplotlib knows about.
Add the following code to your script and run it:
# This command rebuilds Matplotlib's font cache. # Do this if you've recently installed new fonts on your system. font_manager._rebuild()Get a list of all available font families
available_fonts = sorted([f.name for f in font_manager.fontManager.ttflist]) print(“Available Fonts:”) for font in available_fonts: print(f”- {font}“)
This code first tells Matplotlib to rebuild its list of fonts. This is crucial if you've installed new fonts on your computer since the last time you ran Matplotlib. Then, it collects all font names and prints them out. Look through this list to confirm the name of the font you want to use, paying close attention to spelling and capitalization.
Step 3: Change the Global Font Family for All Text
The easiest way to change fonts across your entire Matplotlib plot is to modify the global settings, known as `rcParams` (runtime parameters). This will affect all text elements unless they are specifically overridden later.
You can set the main font family using `font.family`. Matplotlib often groups fonts into general categories like 'serif', 'sans-serif', 'monospace', 'cursive', and 'fantasy'. When you set `font.family` to one of these, Matplotlib will use the first available font from a list associated with that family.
For example, to use a sans-serif font:
# Example: Set a global sans-serif font plt.rcParams['font.family'] = 'sans-serif' plt.rcParams['font.sans-serif'] = ['Helvetica', 'Arial', 'Liberation Sans'] # Fallback orderHere, Matplotlib will try to find 'Helvetica' first. If 'Helvetica' isn't available, it will try 'Arial', then 'Liberation Sans', and so on. You can replace these with font names you found in Step 2.
To use a specific font directly, you can list it as the only option in the family list, or set `font.family` to the font name if it's not a generic family:
# Example: Set a specific global font (e.g., 'Times New Roman' or 'Consolas') plt.rcParams['font.family'] = 'serif' # Or 'monospace' plt.rcParams['font.serif'] = ['Times New Roman', 'DejaVu Serif', 'Computer Modern Roman']Or, if you want to force a specific font as the only option:
plt.rcParams[‘font.family’] = ‘monospace’
plt.rcParams[‘font.monospace’] = [‘Consolas’]
After setting these parameters, any new plot you create will use these font settings for all text.
Step 4: Change Font Size and Weight Globally
Besides the font family, you might want to change the size and weight (boldness) of all text in your plots. This can also be done using `rcParams`.
You can set a global `font.size` for all text and `font.weight` for boldness. Common weights are 'normal', 'bold', 'light', or numerical values.
# Set global font size plt.rcParams['font.size'] = 12Set global font weight (e.g., ‘normal’, ‘bold’, ‘light’)
plt.rcParams[‘font.weight’] = ‘normal’
For specific elements, you can also set sizes
plt.rcParams[‘axes.labelsize’] = 14 # Size for x and y axis labels
plt.rcParams[‘xtick.labelsize’] = 10 # Size for x-axis tick labels
plt.rcParams[‘ytick.labelsize’] = 10 # Size for y-axis tick labels
plt.rcParams[‘legend.fontsize’] = 12 # Size for legend text
plt.rcParams[‘figure.titlesize’] = 16 # Size for figure titles
Adjust the `font.size` to a value that makes your plot text readable without being too large or too small. Experiment with `font.weight` to see what looks best for your data visualization.
Step 5: Override Global Settings for Specific Text Elements
Sometimes you need a different font, size, or weight for a particular part of your plot, like the title or a specific label, without changing everything else. Matplotlib functions that add text to a plot often have `fontdict` or individual `fontname`, `fontsize`, `fontweight` arguments.
Here's how to change the font for titles, axis labels, and legend text specifically:
# Generate some example data x = np.linspace(0, 10, 100) y = np.sin(x)plt.figure(figsize=(8, 6)) plt.plot(x, y, label=‘Sine Wave’)
Change font for the plot title
plt.title(‘My Custom Plot Title’, fontname=‘Times New Roman’, # Use a specific font fontsize=18, fontweight=‘bold’, color=‘navy’)
Change font for the X-axis label
plt.xlabel(‘X-axis Values’, fontname=‘Arial’, # Another font example fontsize=14, fontweight=‘light’, color=‘darkgreen’)
Change font for the Y-axis label
plt.ylabel(‘Y-axis Values’, fontname=‘Verdana’, fontsize=14, fontweight=‘normal’, color=‘purple’)
Change font for the legend text
plt.legend(prop={‘family’: ‘monospace’, ‘size’: 10, ‘weight’: ‘bold’})
plt.grid(True) plt.show()
In this example, `plt.title()`, `plt.xlabel()`, and `plt.ylabel()` all take `fontname`, `fontsize`, and `fontweight` arguments. For `plt.legend()`, you pass a dictionary to the `prop` argument to customize its font properties.
Step 6: Use Fonts from a File (Advanced)
What if the font you want to use isn't installed on your system, or you want to ensure your plot looks the same on any computer without needing to install the font? You can load a font directly from a `.ttf` (TrueType Font) or `.otf` (OpenType Font) file.
First, place your font file (e.g., `MyCustomFont.ttf`) in the same directory as your Python script, or provide its full path.
from matplotlib import font_manager, pyplot as plt import numpy as npPath to your custom font file
font_path = ‘path/to/your/MyCustomFont.ttf’ # Change this to your actual path
Add the font to Matplotlib’s font manager
custom_font_properties = font_manager.FontProperties(fname=font_path)
Example plot
x = np.linspace(0, 10, 100) y = np.cos(x)
plt.figure(figsize=(8, 6)) plt.plot(x, y)
Use the custom font for the title
plt.title(‘Plot with Custom Font’, fontproperties=custom_font_properties, fontsize=16)
Use the custom font for labels (example: x-label)
plt.xlabel(‘Custom X-axis’, fontproperties=custom_font_properties, fontsize=12)
plt.grid(True) plt.show()
By creating a `FontProperties` object from your font file, you can then pass this object to the `fontproperties` argument of Matplotlib functions that accept it, like `plt.title()`, `plt.xlabel()`, `plt.ylabel()`, and `plt.text()`. This ensures the plot uses your exact font, regardless of whether it's globally installed.
Step 7: Reset Matplotlib Settings to Default
If you've made a lot of changes to `rcParams` and want to go back to Matplotlib's default settings, you can easily reset them. This is useful when starting a new plot or when troubleshooting font issues.
To reset all `rcParams` to their default values, use `plt.rcParams.update(plt.rcParamsDefault)`:
# Make some changes (for demonstration) plt.rcParams['font.family'] = 'serif' plt.rcParams['font.size'] = 16This will reset all Matplotlib’s runtime parameters to their factory defaults
plt.rcParams.update(plt.rcParamsDefault)
Now, any new plot will use Matplotlib’s original default fonts and sizes.
print(plt.rcParams[‘font.family’]) # Will show the default, e.g., ‘sans-serif’
print(plt.rcParams[‘font.size’]) # Will show the default, e.g., 10.0
After running `plt.rcParams.update(plt.rcParamsDefault)`, any subsequent plots will revert to the default Matplotlib styling, including its default font choices and sizes.
Quick Reference
| Situation | Use this | Why |
|---|---|---|
| Change font for all text in all future plots | `plt.rcParams['font.family'] = 'serif'` `plt.rcParams['font.sans-serif'] = ['Arial', 'Helvetica']` |
Sets a global style for consistency across your project. |
| Change font for a specific plot title | `plt.title('My Title', fontname='Times New Roman')` | Overrides the global setting for just the title. |
| Change font for axis labels | `plt.xlabel('X-Label', fontname='Verdana')` | Allows specific styling for axis descriptions. |
| Change font for legend text | `plt.legend(prop={'family': 'monospace', 'size': 10})` | Customizes the appearance of the legend to stand out or match. |
| Change global font size | `plt.rcParams['font.size'] = 14` | Adjusts the overall readability of all text. |
| Use a font file directly (not installed) | `custom_font = font_manager.FontProperties(fname='path/to/font.ttf')` `plt.title('Title', fontproperties=custom_font)` |
Ensures consistent font rendering across different systems without installation. |
| Font changes not showing up | `from matplotlib import font_manager` `font_manager._rebuild()` |
Refreshes Matplotlib's cache of available system fonts. |
Common Problems When You Change Matplotlib Font
Font Not Found or Incorrect Default Used
Problem: You set a specific font, but Matplotlib uses a different, generic-looking font instead, or you get an error message about the font not being found.
Solution:
- Check Spelling: Double-check that the font name you entered is spelled exactly as it appears on your system and in Matplotlib's font list (from Step 2). Font names are often case-sensitive.
- Verify Installation: Ensure the font is actually installed on your operating system. If it's a new font, you might need to restart your computer or your Python environment.
- Rebuild Font Cache: Run `from matplotlib import font_manager; font_manager._rebuild()` to force Matplotlib to re-scan for fonts. Do this if you've recently installed new fonts.
- Use Fallbacks: When setting `rcParams['font.sans-serif']` (or `serif`, etc.), provide a list of fallback fonts, like `['MyDesiredFont', 'Arial', 'DejaVu Sans']`. This way, if your main font isn't found, a reasonable alternative will be used.
Font Changes Don't Apply After Modifying `rcParams`
Problem: You've changed `plt.rcParams['font.family']` or `plt.rcParams['font.size']`, but your existing plot elements or even new plots don't show the changes.
Solution:
- Order of Operations: `rcParams` settings must be applied before you create your plot. If you modify `rcParams` after `plt.plot()` or `plt.title()` calls, those already-created elements won't update. Place all `rcParams` modifications at the beginning of your script, after imports.
- Specific Overrides: If you've used `fontname` or `fontproperties` arguments directly in `plt.title()`, `plt.xlabel()`, etc., those local settings will override the global `rcParams`. Check if you have specific overrides that are preventing the global changes from showing.
- New Figure: Sometimes, closing previous figures (`plt.close('all')`) or creating a completely new figure (`plt.figure()`) after changing `rcParams` can help ensure the new settings are applied.
Fonts Appear Blurry or Pixelated
Problem: The text in your plots looks jagged, blurry, or pixelated, especially when saving to certain file formats.
Solution:
- DPI Settings: When saving your plot, increase the Dots Per Inch (DPI). A higher DPI creates a higher-resolution image, making text and lines much sharper. For example: `plt.savefig('my_plot.png', dpi=300)`. Common values are 150, 300, or 600.
- Vector Formats: Save your plots as vector graphics formats like PDF or SVG (`.pdf`, `.svg`). These formats describe shapes and text mathematically, so they scale perfectly without pixelation at any resolution. This is generally the best approach for high-quality output. Example: `plt.savefig('my_plot.pdf')`.
- Matplotlib Version: Ensure your Matplotlib library is up to date (`pip install --upgrade matplotlib`). Newer versions often have rendering improvements.
Advanced Tips for How To Make Matplotlib Change Font
Create Custom Matplotlib Stylesheets (.mplstyle)
For complex projects or if you want to reuse a specific font and plot style across many different scripts, creating a custom Matplotlib stylesheet is highly efficient. A stylesheet is a text file (usually with a `.mplstyle` extension) that contains `rcParams` settings.
How to do it:
- Create a file named `mystyle.mplstyle` (or any other name) in the same directory as your Python script or in Matplotlib's style library directory.
- Inside the file, list your desired `rcParams` settings, one per line: # mystyle.mplstyle font.family: sans-serif font.sans-serif: Helvetica, Arial, DejaVu Sans font.size: 12 axes.labelsize: 14 axes.titlesize: 16 xtick.labelsize: 10 ytick.labelsize: 10 legend.fontsize: 12 figure.titlesize: 18
- In your Python script, load the style using `plt.style.use()`:
import matplotlib.pyplot as plt
import numpy as np
plt.style.use(‘mystyle.mplstyle’) # Loads your custom style
x = np.linspace(0, 10, 100) y = np.sin(x)
plt.figure(figsize=(8, 6)) plt.plot(x, y) plt.title(“Plot with Custom Style”) plt.xlabel(“X-axis”) plt.ylabel(“Y-axis”) plt.show()
This method keeps your code clean and allows you to easily switch between different visual styles by changing just one line. Matplotlib also comes with many built-in styles you can explore.
Embedding Fonts in Saved PDF/SVG Files
When you save your plot to a vector format like PDF or SVG, the font information is usually not embedded by default. This means that if someone views your PDF on a computer without your specific font installed, they might see a different font. You can force Matplotlib to embed the fonts directly into the file.
To enable font embedding, modify `rcParams` before saving:
import matplotlib.pyplot as plt import numpy as npSet your desired font settings
plt.rcParams[‘font.family’] = ‘sans-serif’ plt.rcParams[‘font.sans-serif’] = [‘Arial’, ‘Helvetica’, ‘DejaVu Sans’]
x = np.linspace(0, 10, 100) y = np.cos(x)
plt.figure(figsize=(8, 6)) plt.plot(x, y) plt.title(“Plot with Embedded Font”) plt.xlabel(“X-Axis”) plt.ylabel(“Y-Axis”)
Enable font embedding for PDF files
plt.rcParams[‘pdf.fonttype’] = 42 # Type 42 (TrueType) fonts are embedded plt.rcParams[‘ps.fonttype’] = 42 # For PostScript files
plt.savefig(‘plot_with_embedded_font.pdf’) plt.savefig(‘plot_with_embedded_font.svg’) # SVG files generally embed by default plt.close()
Setting `pdf.fonttype` and `ps.fonttype` to 42 (which represents TrueType fonts) ensures that the fonts used in your plot are embedded within the PDF or PostScript file. This guarantees that your plot will look exactly the same on any system, regardless of its installed fonts.
How To Make Matplotlib Change Font FAQ
Q: How do I find out which fonts Matplotlib can use?
A: You can use the `font_manager` module. Run `from matplotlib import font_manager; available_fonts = sorted([f.name for f in font_manager.fontManager.ttflist]); print(available_fonts)`. This will print a list of all TrueType fonts Matplotlib has found on your system.
Q: My font isn't showing up, even after setting `rcParams`. What's wrong?
A: The most common reasons are: 1) The font name is misspelled or incorrectly capitalized. 2) The font is not actually installed on your system. 3) Matplotlib's font cache needs to be rebuilt (run `font_manager._rebuild()`). 4) You're trying to change the font after the plot elements have already been created, or a specific element's font is being overridden by a local setting (e.g., `fontname` in `plt.title()`).
Q: Can I use a font that isn't installed on my computer?
A: Yes, you can load a font directly from a `.ttf` or `.otf` file using `font_manager.FontProperties(fname='path/to/your/font.ttf')` and then passing this `FontProperties` object to the `fontproperties` argument of Matplotlib functions (e.g., `plt.title(..., fontproperties=custom_font)`).
Q: How do I change the font for just the tick labels on the axes?
A: You can set specific `rcParams` for tick labels: `plt.rcParams['xtick.labelsize'] = 12` for X-axis labels and `plt.rcParams['ytick.labelsize'] = 12` for Y-axis labels. You can also use `ax.tick_params(labelsize=12)` for more general tick label control on a specific axes object.
Q: What's the difference between `font.family` and `font.sans-serif` in `rcParams`?
A: `font.family` tells Matplotlib which general category of font to use (e.g., 'serif', 'sans-serif', 'monospace'). `font.sans-serif` (or `font.serif`, `font.monospace`) is a list of specific font names that fall into that category, in order of preference. If `font.family` is set to 'sans-serif', Matplotlib will try to use the first available font from the `font.sans-serif` list.
Final Checklist for How To Make Matplotlib Change Font
- You have Python and Matplotlib installed and ready.
- You know the exact name of the font you want to use, or you have its `.ttf` or `.otf` file.
- All `matplotlib.rcParams` changes are placed at the beginning of your script, before any plotting commands.
- You've used `font_manager._rebuild()` if you installed new fonts recently.
- You've used fallback font names in `rcParams` lists (e.g., `['MyFont', 'Arial', 'DejaVu Sans']`) for robustness.
- You've considered using specific `fontname` or `fontproperties` arguments for individual plot elements like titles or labels when global settings aren't enough.
- You've tested your plot to ensure the desired fonts are appearing correctly.
- For high-quality output, you've saved to a vector format (PDF/SVG) and considered embedding fonts.
- You know how to reset Matplotlib settings to default if needed using `plt.rcParams.update(plt.rcParamsDefault)`.