Font-related issues in python (字体缺失解决方案)

Error message:

findfont: Generic family ‘sans-serif’ not found because none of the following families were found: Noto Sans CJK SC

Solution 1: It looks like you’re running into font-related issues, likely when using Matplotlib or another visualization library in Python. The warnings indicate that the system can’t find the Noto Sans CJK SC font and that some Chinese characters (e.g., 测试中文) are missing from the default font.

Potential Fixes

1. Install the Missing Fonts

Try installing the Noto Sans CJK SC font manually:

  • On Ubuntu/Debian:bash Copy “sudo apt update sudo apt install fonts-noto-cjk
  • On macOS (using Homebrew):bash Copy “brew tap homebrew/cask-fonts brew install --cask font-noto-sans-cjk
  • On Windows:
    • Download the fonts from Google Fonts.
    • Install them by double-clicking the .ttf or .otf files and selecting “Install.”

2. Explicitly Set a Font in Matplotlib

If you don’t need Noto Sans CJK SC, you can set another font that supports Chinese characters, like Arial Unicode MS:

In python copy below:

import matplotlib.pyplot as plt
import matplotlib

# Set font to avoid missing glyphs
matplotlib.rcParams['font.sans-serif'] = ['Arial Unicode MS'] 
matplotlib.rcParams['axes.unicode_minus'] = False  # Ensure minus signs display correctly

# Test plot
plt.plot([1, 2, 3], [4, 5, 6])
plt.title("测试中文")
plt.show()

3. Clear Matplotlib Font Cache

If you’ve installed the font but still see errors, clear the font cache:

bash copy below in Terminals: rm ~/.cache/matplotlib -rf

Then restart your Python session.

copy paste below:

import matplotlib.pyplot as plt

import matplotlib

# Set to use a more generic font

matplotlib.rcParams[“font.sans-serif”] = [“Arial Unicode MS”]  # Try other CJK-compatible fonts

matplotlib.rcParams[“axes.unicode_minus”] = False  # Avoid issues with negative signs

# Test plot

plt.plot([1, 2, 3], [4, 5, 6])

plt.title(“测试中文”)  # This should display correctly

plt.show()