Solve python using matplotlib to draw Chinese garbled characters

This article has participated in the "Newcomer Creation Ceremony" event to start the road of gold creation together.

foreword

  • In Python programming, we often need to use matplotlib for drawing (scientific research papers, data analysis, etc.). When we need to set Chinese descriptions for titles or coordinates, the default matplotlib settings will encounter the problem of displaying a box shape. , you need to solve this problem by modifying the matplotlib configuration file or setting the specified Chinese font directly in the code. This article will introduce the specific steps of the two methods and the comparison of the methods!
  • There are two types of solutions: permanent and temporary

If this article is helpful to you, you may wish to click three links! Your support and attention are the driving force for bloggers to create!

References

www.pianshen.com/article/296…

Workaround (set font dynamically)

  • Permanent settings: modify the matplotlib configuration file

    • View the configuration file path:

    Note: If you use the conda virtual environment, pay attention to entering the corresponding environment and then execute the following commands, otherwise the modified configuration file may not be the corresponding environment!

    import matplotlib
    matplotlib.matplotlib_fname()
    复制代码
    • Add Chinese fonts to the ttf folder [This article sets the simhei font (click to download) ]

    • Modify the configuration file:

      ①Remove the comment:image.png

      ②Remove the comment and add the Chinese font name (the Chinese font name added to the ttf folder):image.png

      ③ Remove the comment:image.png

  • Temporary settings: specify the font in the code (convenient to customize the font, personal recommendation)

    import matplotlib
    matplotlib.matplotlib_fname()
    复制代码
    • Set the font of the drawing in the code
    import matplotlib
    
    matplotlib.rcParams['font.sans-serif'] = ['SimHei']
    matplotlib.rcParams['font.family']='sans-serif'
    #解决负号'-'显示为方块的问题
    matplotlib.rcParams['axes.unicode_minus'] = False
    复制代码
    • After that, you can draw normally and set the Chinese information.
  • Method comparison:

method Temporary modification permanent modification
flexibility Flexible font modification Fixed setting font
Convenience Each py file needs to be set Set once, take effect forever

Guess you like

Origin juejin.im/post/7082344514655879176