In the Online Python Runner (Python 3.12.7), users can go beyond the built-in Alibaba PuHuiTi
font and upload and use custom fonts. This guide walks you through the complete process of configuring and using custom fonts directly in your browser—ideal for learning, teaching, or visual customization.
Why Use Custom Fonts?
- The default font style doesn’t meet your design needs (e.g., you prefer Source Han Sans, ZCOOL KuaiLe, etc.)
- Brand consistency (e.g., using a company-specific typeface)
- Educational purposes (e.g., demonstrating how Matplotlib loads fonts)
⚠️ Note: If you only need to display Chinese text, use the built-in
Alibaba PuHuiTi
—no extra steps required.
Step-by-Step Guide
Step 1: Prepare the Font File
- Download a
.ttf
or.otf
font file (e.g.,ZCOOLKuaiLe-Regular.ttf
) - Ensure you have the legal right to use the font (check its license)
Step 2: Upload the Font to the Virtual File System
- In the tool interface, go to File List → Upload File
- Select your local font file (e.g.,
myfont.ttf
) - After upload, the file will be available in the current working directory (e.g.,
./myfont.ttf
)
Step 3: Register and Enable the Font in Code
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
# 1. Register the font file (use the correct path)
font_path = './myfont.ttf' # Replace with your actual filename
fm.fontManager.addfont(font_path)
# 2. (Optional) Verify the font name
font_prop = fm.FontProperties(fname=font_path)
font_name = font_prop.get_name()
print("Loaded font name:", font_name)
# 3. Set as default sans-serif font
plt.rcParams['font.sans-serif'] = [font_name]
plt.rcParams['axes.unicode_minus'] = False # Ensures minus signs display correctly
# 4. Test plotting
plt.figure(figsize=(6, 3))
plt.text(0.5, 0.5, "Custom Font Example", fontsize=20, ha='center')
plt.axis('off')
plt.show()
# 5. Save the image
plt.savefig('custom_font_demo.png')
plt.close()
Troubleshooting & Tips
Q1: How do I confirm the font was loaded?
List all available fonts or search by keyword:
import matplotlib.font_manager as fm
# List all font names
names = {f.name for f in fm.fontManager.ttflist}
print(sorted(names))
# Search for a specific font
target = "KuaiLe" # Replace with your expected font keyword
matches = [n for n in names if target.lower() in n.lower()]
print("Matches:", matches)
Q2: Why does the text still show as boxes or garbled characters?
- Double-check the
font_path
(case-sensitive and exact) - Ensure the file is a valid TrueType (.ttf) or OpenType (.otf) font
- Use the font’s family name (not the filename) in
plt.rcParams
Q3: Can I use multiple custom fonts?
Yes. Register each font separately and apply them using FontProperties
:
from matplotlib import font_manager
prop1 = font_manager.FontProperties(fname='./font1.ttf')
prop2 = font_manager.FontProperties(fname='./font2.ttf')
plt.text(0.2, 0.5, "Font 1", fontproperties=prop1)
plt.text(0.6, 0.5, "Font 2", fontproperties=prop2)
plt.axis('off')
plt.show()
Example: Using “ZCOOL KuaiLe” for Chinese Text
Assume you’ve uploaded ZCOOLKuaiLe-Regular.ttf
:
Download link:https://pan.baidu.com/s/15FMvEHiL_9T3JV71tw3e8Q?pwd=eb5y
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
# Register the font
fm.fontManager.addfont('./ZCOOLKuaiLe-Regular.ttf')
# Set as default font
plt.rcParams['font.sans-serif'] = ['ZCOOL KuaiLe']
plt.rcParams['axes.unicode_minus'] = False
# Plot
plt.figure(figsize=(5, 2))
plt.title("Welcome to Custom Fonts!")
plt.text(0.5, 0.5, "Hello 中文", fontsize=24, ha='center')
plt.axis('off')
plt.show()
plt.savefig('zcool_demo.png')
plt.close()
✅ Key Insight:
'ZCOOL KuaiLe'
is the font’s family name, which you can obtain viaFontProperties(fname=...).get_name()
.
Important Notes
- Session Isolation: Uploaded files (including fonts) are lost when you close the browser tab. Re-upload if needed.
- Performance: Avoid repeatedly registering fonts; do it once at the start of your script.
- Licensing: Only use fonts that are free for commercial use or properly licensed.
- Avoid Overriding System Fonts: Never hardcode
plt.rcParams['font.sans-serif'] = "SimHei"
—this breaks the built-in Chinese font support.
Summary
Using custom fonts in the online Python environment requires just three steps: Upload → Register → Configure. This approach is not only practical for personalized visualizations but also an excellent way to learn how Matplotlib handles fonts.
Try it now: https://toolshu.com/python3
Article URL:https://toolshu.com/en/article/8ttg4bsj
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License 。
Loading...