[Python] Custom Font in Google Colab matplotlib graphs & figures
To use a custom font in matplotlib graphs and figures in Google Colab, it isn’t as straightforward as in a local Python environment (e.g., Jupyter Notebook), where you can configure fonts using rcParams
as follows:
import matplotlib.pyplot as plt
from matplotlib import rcParams
rcParams['font.family'] = 'Arial' # Or any other font you want
In Google Colab, using rcParams
alone will result in errors (“WARNING:matplotlib.font_manager:findfont: Font family 'Arial' not found.
“) However, there is a solution that works for Colab, allowing you to globally apply custom fonts to all graphs generated in the notebook.
Steps to Set Custom Fonts in Google Colab
1. Install Font: First, ensure that the custom font you want to use is saved in your mounted drive. Colab doesn’t have the same fonts as your local machine by default. You can install custom fonts directly by downloading them and placing them in the mounted drive directory. I saved the font “Arial” in the drive. The first step is to mount Google Drive to load your downloaded font.
from google.colab import drive
drive.mount('/content/drive')
2. Load, Register, and Set the Global Font: Then, you can load the font from your file path that you saved your font. You can use the following code by changing the path and font names.
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
from pathlib import Path
# Path to the Arial font file
fpath = Path("/content/drive/My Drive/Arial.ttf")
# Load and register the Arial font
arial_font = fm.FontProperties(fname=fpath)
fm.fontManager.addfont(fpath) # Add the font to Matplotlib's font manager
# Set the global font to Arial
plt.rcParams['font.family'] = arial_font.get_name()
You can test if it has been set successfully or not by using the following codes:
# Now, all plots will use Arial without specifying fontproperties manually
fig, ax = plt.subplots()
ax.set_title('This is a special font: Arial')
ax.set_xlabel('This is the default font')
plt.show()
Reference
https://stackoverflow.com/questions/78530095/how-to-use-arial-on-matplotlib-via-google-colab