Small knowledge, big challenge! This paper is participating in theEssentials for programmers”Creative activities

Hello, everyone, I am my old cousin, today to share a permanent solution to matplotlib Chinese garble notes, hope to help you.

First, you need to have the Python environment installed and Python development tools installed on your computer.

If you haven’t installed it yet, check out the following article:

If you only use Python to process data, crawlers, data analysis, automatic scripts, and machine learning, you are advised to use the Python basic environment and Jupyter. For details, see Windows/Mac Installation and Using The Python Environment and Jupyter Notebook

If you want to use Python to develop web projects, you are advised to use the Python foundation environment +Pycharm to install and use Python/ Pycharm.

Download the boldface Chinese font library first. Here I have already downloaded it. You can get the download address by simply saying Python reply: font on wechat.

  • View the matplotlib installation directory
import matplotlib
Check the installation path
print(matplotlib.get_data_path()) 

"'/Users/HHH/Library/Python / 3.7 / lib/Python/site - packages/matplotlib/MPL - data ' ' '
Copy the code
  • Copy the downloaded font tompl-data/fonts/ttfdirectory

  • Modify the matplotlib Settings file inmpl-data/matplotlibrc, use text mode to open, modify three places, save after modification:
Font-family: 'SimHei', 'SimHei', 'SimHei', 'SimHei', 'SimHei', 'SimHei'; SimHei, DejaVu Sans, Bitstream ... Unicode_minus: False axes. Unicode_minus: FalseCopy the code
  • We need to reload the font configuration

If your matplotlib is less than 3+, you can do this with the following code:

from matplotlib.font_manager import _rebuild
_rebuild()
Copy the code

If your Matplotlib is 3+ or higher, the private _rebuild method is deprecated in these versions, so you can’t reload using the above method, but more simply, you just need to restart your Python environment.

Take Jupyter as an example, click the button below to restart the kernel, and then run the code to display Chinese.If that still doesn’t work, check the Matplotlib cache location, delete it, and restart the Jupyter Notebook.

# matplotlib Cache directory
import matplotlib 
print(matplotlib.get_cachedir())
'''
/Users/hhh/.matplotlib
'''
Copy the code

This little drawing example is also for you to check.

# Draw a random pie chart
import matplotlib.pyplot as plt

fig1 = plt.figure()  Create an image object
plt.pie([0.5.0.3.0.2].# value
        labels=['我'.'you'.'it'].# label
        explode=(0.0.2.0),  # (burst) distance
        autopct='% 1.1 f % %'.# display percentage format
        shadow=True)  # whether to show shadows
plt.show() 
Copy the code